﻿using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Collections.Generic;
using Kingdee.BOS;
using Kingdee.BOS.Log;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Orm.DataEntity;
using Newtonsoft.Json.Linq;
using System.Web.Security;
using KingdeeWebServiceProject.Data;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.WebApi.FormService;
using Kingdee.BOS.Util;
using SqlObject = Kingdee.BOS.App.Data.SqlObject;

namespace KingdeeWebServiceProject
{
    //零售系统会员、卡券服务类
    internal class VIPCardService
    {
        public static string saleFormId = "QUDE_BiddingSalesOrder";
        public static string purchaseFormId = "QUDE_BiddingPurchaseOrder";
        public static string transFormId = "ora_CompetitiveTransaction";

        #region 新增交易单
        internal string AddBiddingTransData(Context ctx,string OrderNo, string OrgNumber, string BuyerNumber, decimal PurAmount, string SellerNumber, decimal SaleAmount, decimal SalesProfit, decimal PurQty, decimal PurPrice, decimal SalQty, decimal SalPrice, string MaterialNumber, JObject result)
        {
            result["Result"] = false;
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            JObject rsObj;
            string Number = string.Empty;
            try
            {
                #region 竞价销售
                decimal FServiceRate = 0;
                decimal FPurRate = 0;
                int FORGID = 0;
                string FBCurrencyId = string.Empty;
                DateTime curdate = DateTime.Now;
                string StockNumber = string.Empty;
                string PurBillno = "";
                string SaleBillno = "";

                string SQL = string.Format("SELECT FORGID FROM T_ORG_ORGANIZATIONS WHERE FNUMBER = '{0}'", OrgNumber);
                DynamicObjectCollection dynamicObjectCollection = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjectCollection != null) && (dynamicObjectCollection.Count > 0))
                {
                    FORGID = Convert.ToInt32(dynamicObjectCollection.First()["FORGID"]);
                }

                SQL = string.Format(@"/*dialect*/SELECT
	                                        t1.FNUMBER 
                                        FROM
	                                        T_BD_STOCK t1
                                        WHERE
	                                        FUSEORGID = {0}", FORGID);

                dynamicObjectCollection = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjectCollection != null) && (dynamicObjectCollection.Count > 0))
                {
                    StockNumber = dynamicObjectCollection.First()["FNUMBER"].ToString();
                }

                SQL = string.Format(@"/*dialect*/SELECT
                                                    F_QUDE_SalesFee,F_QUDE_PROCUREMENTFEE
                                                FROM
                                                    ora_t_Patformparameter
                                                WHERE F_ORA_ORGID = {0}
                                                ", FORGID);

                dynamicObjectCollection = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjectCollection != null) && (dynamicObjectCollection.Count > 0))
                {
                    FServiceRate = Convert.ToDecimal(dynamicObjectCollection.First()["F_QUDE_SalesFee"]);
                    FPurRate = Convert.ToDecimal(dynamicObjectCollection.First()["F_QUDE_PROCUREMENTFEE"]);
                }



                JArray details = new JArray();

                decimal sellerQty = 0;
                decimal sellerAmount = 0;

                decimal FSalAmount = Convert.ToDecimal(SalPrice);
                decimal FSellingPrice = FSalAmount * (1 - FServiceRate);
                decimal FTotalAmount = SalQty * FSellingPrice;

                sellerQty += SalQty;
                sellerAmount += FTotalAmount;

                JObject entity = new JObject
                {
                    {
                        "FWineCode",
                        new JObject {
                            { "FNumber", MaterialNumber }
                        }
                    },
                    { "FBottlesSold", SalQty },
                    { "FSellingPrice", SalPrice },
                    { "FActualPrice", FSellingPrice },
                    { "FServiceRate", FServiceRate },
                    { "FTotalAmount", FTotalAmount }
                };
                details.Add(entity);

                JObject head = new JObject
                {
                    { "FApplicationDate", curdate.ToString("yyyy-MM-dd 00:00:00") },
                    { "FBeginDate", curdate.ToString("yyyy-MM-dd 00:00:00") },
                    { "FSubmitDate", curdate.ToString("yyyy-MM-dd 00:00:00") },
                    { "FEndDate", curdate.AddMonths(2).ToString("yyyy-MM-dd 00:00:00") },
                    { "FTransactions", 2 },
                    { "FSaleQty", sellerQty },
                    { "FALLAmount", sellerAmount },
                    {
                        "FApplicationOrgId",
                        new JObject {
                            { "FNumber", OrgNumber }
                        }
                    },
                    {
                        "FBCurrencyId",
                        new JObject {
                            { "FNumber", FBCurrencyId }
                        }
                    },
                    {
                        "F_QUDE_Merchant",
                        new JObject {
                            { "FNumber", SellerNumber }
                        }
                    },
                    {
                        "F_QUDE_Stock",
                        new JObject {
                            { "FNumber", StockNumber }
                        }
                    },
                    { "FEntity", details }
                };

                JObject jsonData = new JObject
                {
                    { "Model", head }
                };
                bool flag = false;
                rsObj = CommonService.SaveMethod(ctx, saleFormId, jsonData.ToString());
                if (CommonService.GetJParamString(rsObj, "code") == "200")
                {
                    Number = CommonService.GetJParamString(rsObj, "Number");
                    JObject jobj = new JObject
                    {
                        { "Numbers", Number }
                    };
                    keyValuePairs.Add("QUDE_Bidding_SalesOrder", Number);
                    rsObj = CommonService.SubmitMethod(ctx, saleFormId, jobj.ToString());
                    if (CommonService.GetJParamString(rsObj, "code") == "200")
                    {
                        rsObj = CommonService.AuditMethod(ctx, saleFormId, jobj.ToString());
                        if (CommonService.GetJParamString(rsObj, "code") == "200")
                        {
                            SaleBillno = Number;
                            flag = true;
                        }
                    }
                }

                if (!flag)
                {
                    DeleteBatchBill(ctx, keyValuePairs);
                    result["Message"] = string.Format("竞价销售单新增异常，详情：{0}！", CommonService.GetJParamString(rsObj, "msg"));
                    return result.ToString();
                }
                #endregion

                #region 竞价采购单
                details = new JArray();

                decimal buyerQty = 0;
                decimal buyerAmount = 0;

                decimal FPurPrice = Convert.ToDecimal(PurPrice);
                FSellingPrice = FPurPrice * (1 + FPurRate);
                FTotalAmount = PurQty * FSellingPrice;

                buyerQty += PurQty;
                buyerAmount += FTotalAmount;

                entity = new JObject
                {
                    {
                        "FWineCode",
                        new JObject {
                            { "FNumber", MaterialNumber }
                        }
                    },
                    { "FPurchaseSold", PurQty },
                    { "FPurchasePrice", FPurPrice },
                    { "FPurchaseCost", FSellingPrice },
                    { "FServiceRate", FPurRate },
                    { "FTotalAmount", FTotalAmount }
                };
                details.Add(entity);

                head = new JObject
                {
                    { "FApplicationDate", curdate.ToString("yyyy-MM-dd 00:00:00") },
                    { "FBeginDate", curdate.ToString("yyyy-MM-dd 00:00:00") },
                    { "FSubmitDate", curdate.ToString("yyyy-MM-dd 00:00:00") },
                    { "FEndDate", curdate.AddMonths(2).ToString("yyyy-MM-dd 00:00:00") },
                    { "FTransactions", 2 },
                    { "FPurchaseQty", buyerQty },
                    { "FALLAmount", buyerAmount },
                    {
                        "FApplicationOrgId",
                        new JObject {
                            { "FNumber", OrgNumber }
                        }
                    },
                    {
                        "FBCurrencyId",
                        new JObject {
                            { "FNumber", FBCurrencyId }
                        }
                    },
                    {
                        "F_QUDE_Merchant",
                        new JObject {
                            { "FNumber", BuyerNumber }
                        }
                    },
                    {
                        "F_SUP_Merchant",
                        new JObject {
                            { "FNumber", SellerNumber }
                        }
                    },
                    {
                        "F_QUDE_Stock",
                        new JObject {
                            { "FNumber", StockNumber }
                        }
                    },
                    { "FEntity", details }
                };

                jsonData = new JObject
                {
                    { "Model", head }
                };

                flag = false;
                rsObj = CommonService.SaveMethod(ctx, purchaseFormId, jsonData.ToString());
                if (CommonService.GetJParamString(rsObj, "code") == "200")
                {
                    Number = CommonService.GetJParamString(rsObj, "Number");
                    JObject jobj = new JObject
                    {
                        { "Numbers", Number }
                    };
                    keyValuePairs.Add("QUDE_BiddingPurchaseOrder", Number);
                    rsObj = CommonService.SubmitMethod(ctx, purchaseFormId, jobj.ToString());
                    if (CommonService.GetJParamString(rsObj, "code") == "200")
                    {
                        rsObj = CommonService.AuditMethod(ctx, purchaseFormId, jobj.ToString());
                        if (CommonService.GetJParamString(rsObj, "code") == "200")
                        {
                            PurBillno = Number;
                            flag = true;
                        }
                    }
                }

                if (!flag)
                {
                    DeleteBatchBill(ctx, keyValuePairs);
                    result["Message"] = string.Format("竞价采购单新增异常，详情：{0}！", CommonService.GetJParamString(rsObj, "msg"));
                    return result.ToString();
                }
                #endregion

                #region 竞价交易
                head = new JObject
                {
                    { "FBillNo", OrderNo },
                    { "F_PIYZ_Date", curdate.ToString("yyyy-MM-dd 00:00:00") },
                    { "F_PIYZ_Date1", curdate.ToString("yyyy-MM-dd 00:00:00") },
                    { "F_PIYZ_Date2", curdate.AddMonths(2).ToString("yyyy-MM-dd 00:00:00") },
                    { "FSalesProfit", SalesProfit },
                    { "F_QUDE_PurAmount", PurAmount },
                    { "F_QUDE_SaleAmount", SaleAmount },
                    { "F_PIYZ_Amount1",  SalPrice * SalQty },
                    {
                        "F_PIYZ_OrgId",
                        new JObject {
                            { "FNumber", OrgNumber }
                        }
                    },
                    {
                        "F_PIYZ_OrgId2",
                        new JObject {
                            { "FNumber", OrgNumber }
                        }
                    },
                    {
                        "F_QUDE_Buy",
                        new JObject {
                            { "FNumber", BuyerNumber }
                        }
                    },
                    {
                        "F_QUDE_Saler",
                        new JObject {
                            { "FNumber", SellerNumber }
                        }
                    }
                };

                //采购
                details = new JArray();
                entity = new JObject
                {
                    {
                        "F_ora_Merchant",
                        new JObject {
                            { "FNumber", BuyerNumber }
                        }
                    },
                    {
                        "F_PIYZ_Base1",
                        new JObject {
                            { "FNumber", MaterialNumber }
                        }
                    },
                    { "F_PIYZ_Qty", PurQty },
                    { "F_PIYZ_Price", FPurPrice },
                    { "F_PIYZ_Amount", FPurPrice * PurQty },
                    { "F_PIYZ_Qty2", PurQty }
                };
                details.Add(entity);
                head.Add("FEntity", details);

                //销售
                details = new JArray();
                entity = new JObject
                {
                    {
                        "F_ora_MerchantM",
                        new JObject {
                            { "FNumber", SellerNumber }
                        }
                    },
                    {
                        "F_PIYZ_Base11",
                        new JObject {
                            { "FNumber", MaterialNumber }
                        }
                    },
                    { "F_PIYZ_Qty3", SalQty },
                    { "F_PIYZ_Price2", SalPrice },
                    { "F_PIYZ_Amount4", SalPrice * SalQty },
                    { "F_PIYZ_Qty21", SalQty }
                };
                details.Add(entity);
                head.Add("FEntity1", details);

                jsonData = new JObject
                {
                    { "Model", head }
                };

                flag = false;
                rsObj = CommonService.SaveMethod(ctx, transFormId, jsonData.ToString());
                if (CommonService.GetJParamString(rsObj, "code") == "200")
                {
                    Number = CommonService.GetJParamString(rsObj, "Number");
                    JObject jobj = new JObject
                    {
                        { "Numbers", Number }
                    };
                    keyValuePairs.Add("ora_CompetitiveTransaction", Number);
                    rsObj = CommonService.SubmitMethod(ctx, transFormId, jobj.ToString());
                    if (CommonService.GetJParamString(rsObj, "code") == "200")
                    {
                        rsObj = CommonService.AuditMethod(ctx, transFormId, jobj.ToString());
                        if (CommonService.GetJParamString(rsObj, "code") == "200")
                        {
                            flag = true;
                            SQL = string.Format(@"/*dialect*/update QUDE_BiddingPurchaseOrder set FTransactionCode = '{0}' where FBILLNO = '{1}'", OrderNo, PurBillno);
                            DBUtils.Execute(ctx, SQL);
                            SQL = string.Format(@"/*dialect*/update QUDE_Bidding_SalesOrder set FTransactionCode = '{0}' where FBILLNO = '{1}'", OrderNo, SaleBillno);
                            DBUtils.Execute(ctx, SQL);

                        }
                    }
                }

                if (!flag)
                {
                    DeleteBatchBill(ctx, keyValuePairs);
                    result["Message"] = string.Format("竞价交易单新增异常，详情：{0}！", CommonService.GetJParamString(rsObj, "msg"));
                    return result.ToString();
                }

                result["Result"] = true;
                result["Message"] = "新增交易单成功！";
                JObject Data = new JObject
                {
                    { "BillNo", Number }
                };
                result["Data"] = Data;
                return result.ToString();
                #endregion
            }
            catch (Exception ex)
            {
                DeleteBatchBill(ctx, keyValuePairs);
                result["Result"] = false;
                result["Message"] = string.Format("新增交易单失败，原因：{0}", ex.Message);
            }
            return result.ToString();
        }
        #endregion

        internal void DeleteBatchBill(Context ctx, Dictionary<string, string> keyValuePairs)
        {
            try
            {
                List<SqlObject> list = new List<SqlObject>();
                foreach (var item in keyValuePairs)
                {
                    string SQL = string.Format(@"DELETE FROM {0} WHERE FBILLNO = @FBILLNO", item.Key);
                    List<SqlParam> paramList = new List<SqlParam>
                    {
                        new SqlParam("@FBILLNO", KDDbType.String, item.Value)
                    };
                    list.Add(new SqlObject(SQL, paramList));
                }
                if (list.Count > 0)
                {
                    DBUtils.ExecuteBatch(ctx, list);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        //邀请码查询
        internal string QueryInvitationCode(Context ctx, string InvitationCode, string AreaNumber, string StafPhone, JObject result)
        {
            result["Result"] = false;
            try
            {
                if (!string.IsNullOrWhiteSpace(AreaNumber))
                {
                    AreaNumber = string.Format(" AND T4.FNUMBER = '{0}'", AreaNumber);
                }
                if (!string.IsNullOrWhiteSpace(StafPhone))
                {
                    StafPhone = string.Format("AND secl.FPHONE = '{0}'", StafPhone);
                }
                if (!string.IsNullOrWhiteSpace(InvitationCode))
                {
                    InvitationCode = string.Format("AND t1.FINVITATIONCODE = '{0}'", InvitationCode);
                }
                string sql = string.Format(@"/*dialect*/select 
                                                        t3.FNAME AS StafName,
                                                        t4.FNUMBER AreaNumber,
                                                        t5.FNAME AreaName,
                                                        t14.FNAME  AS Currency,
                                                        t12.FSYSMBOL AS SysMbol,
                                                        t1.FINVITATIONCODE AS InvitationCode
                                                        from V_BD_SALESMAN t
                                                        inner join T_BD_OPERATORENTRY t1 on t1.FSTAFFID = t.FSTAFFID and t.FBizOrgId = t1.FBizOrgId
                                                        inner join T_ORG_ORGANIZATIONS t4 on t4.FORGID = t1.FBizOrgId
                                                        inner join T_ORG_ORGANIZATIONS_L t5 on t5.FORGID = t4.FORGID and t5.FLOCALEID = 2052
                                                        inner join V_BD_SALESMAN_L t3 on t3.fid = t.fid  and t3.FLocaleID = 2052
                                                        INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t4.FORGID
                                                        INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                        INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                        INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                                        INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = 2052
                                                        INNER JOIN T_SEC_user secl on secl.FNAME = t3.FNAME
                                                        where 1 =1  {0} {1} {2} ", InvitationCode, AreaNumber, StafPhone);

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    JObject jVipData = JObject.FromObject(Datas.First());

                    result["Result"] = true;
                    result["Message"] = "邀请码查询成功！";
                    result["Data"] = jVipData;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "邀请码查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("邀请码查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }


        //交易记录列表查询
        internal string QueryTransactionList(Context ctx, string OrgNumber, string MaterialNumber, int iPageSize, int iPageNum, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"/*dialect*/select * from (select ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.F_QUDE_DATE, 120) DESC) AS FIDENTITYID,count(1) over() as TotalCount,
                                                        CONVERT(varchar(100),t.F_QUDE_DATE , 120) as Date,t1.F_PIYZ_Qty as Qty,t1.F_PIYZ_PRICE as Amount from ora_CompetitiveTransaction t 
                                                        inner join ora_TransactionEntryM t1 on t1.FID  = t.FID
                                                        inner join T_BD_MATERIAL t2 on t2.FMATERIALID = t1.F_PIYZ_Base1
                                                        inner join T_ORG_ORGANIZATIONS t3 on t3.FORGID = t.F_PIYZ_ORGID
                                                        where t.F_PIYZ_BILLSTATUS = 2 and  t3.FNUMBER = '{0}' and  t2.FNUMBER = '{3}') t
                                                where  t.FIDENTITYID between {1} and {2}", OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, MaterialNumber);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "交易记录列表查询成功";
                    result["TotalCount"] = Convert.ToInt64(Datas.First()["TotalCount"]);
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "交易记录列表查询成功，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("交易记录列表查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //销售员列表查询
        internal string QuerySalerList(Context ctx, string OrgNumber, string SalerName, int iPageSize, int iPageNum, JObject result)
        {
            result["Result"] = false;
            try
            {
                if (!string.IsNullOrWhiteSpace(SalerName))
                {
                    SalerName = "%" + SalerName + "%";
                    SalerName = string.Format("AND  t1.FNAME like '{0}'", SalerName);
                }
                string sql = string.Format(@"/*dialect*/select * from (select ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.FCreateDate, 120) DESC) AS FIDENTITYID,
                                                count(1) over() as TotalCount, t1.FNAME as SalerName from V_BD_SALESMAN t 
                                                inner join V_BD_SALESMAN_L t1 on t1.fid = t.fid
                                                inner join T_ORG_ORGANIZATIONS t2 on t2.FORGID = t.FBIZORGID
                                                where t2.FNUMBER = '{0}' {3} ) t
                                                where  t.FIDENTITYID between {1} and {2}", OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, SalerName);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "销售员列表查询成功";
                    result["TotalCount"] = Convert.ToInt64(Datas.First()["TotalCount"]);
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "销售员列表查询成功，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("销售员列表查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        #region 用户注册
        internal string NewCreateUser(Context ctx, string Name, string SalerName, string Mobile,string OrgNumber, JObject result)
        {
            result["Result"] = false;
            string UserNumber = "";
            string CommonContactNumber = "";
            string CustomerNumber = "";
            string CustomerName = "";
            string StoresfilesNumber = "";
            string SalerNumber = "";
            JObject Data = new JObject();
            try
            {
                string sql = string.Format(@"select 
                                                        t.FNUMBER as Number 
                                                        from V_BD_SALESMAN t 
                                                        inner join V_BD_SALESMAN_L t1 on t1.fid = t.fid
                                                        inner join T_ORG_ORGANIZATIONS t2 on t2.FORGID = t.FBIZORGID
                                                        where t2.FNUMBER = '{0}' and t1.FNAME = '{1}'", OrgNumber, SalerName);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    SalerNumber = Datas.First()["Number"].ToString();
                }
                else
                {
                    
                }
                //第一步先创建星空用户
                string CreateUserStr = CommonService.CreateUser.Replace("用户账号", Name).Replace("用户名称", Name).Replace("电话", Mobile);
                JObject resule = CommonService.SaveMethod(ctx, "SEC_User", CreateUserStr);
                if (CommonService.GetJParamString(resule, "code") == "200")
                {
                    //创建联系人
                    string CreateCommonContact = CommonService.CreateCommonContact.Replace("用户名称", Name).Replace("电话", Mobile);
                    resule = CommonService.SaveMethod(ctx, "BD_CommonContact", CreateCommonContact);
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        //联系人编码
                        CommonContactNumber = CommonService.GetJParamString(resule, "Number");
                        //销售员取数
                        sql = string.Format(@"select 
                                                        t.FNUMBER as Number 
                                                        from V_BD_SALESMAN t 
                                                        inner join V_BD_SALESMAN_L t1 on t1.fid = t.fid
                                                        inner join T_ORG_ORGANIZATIONS t2 on t2.FORGID = t.FBIZORGID
                                                        where t2.FNUMBER = '{0}' and t1.FNAME = '{1}'", OrgNumber, SalerName);
                        Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                        if (Datas != null && Datas.Count > 0)
                        {
                            SalerNumber = Datas.First()["Number"].ToString();
                        }
                        else
                        {

                        }
                        if (OrgNumber == "100")
                        {
                            CustomerName = Name + ",珠三角";
                        }
                        else if (OrgNumber == "102")
                        {
                            CustomerName = Name + ",澳门";
                        }
                        else if (OrgNumber == "103")
                        {
                            CustomerName = Name + ",香港";
                        }
                        else if (OrgNumber == "104")
                        {
                            CustomerName = Name + ",法国";
                        }
                        //创建客户
                        string CreateCustomer = CommonService.CreateCustomer.Replace("区域", OrgNumber).Replace("名称", CustomerName).Replace("销售员", SalerNumber).Replace("联系人编码", CommonContactNumber);
                        resule = CommonService.SaveMethod(ctx, "BD_Customer", CreateCustomer);
                        if (CommonService.GetJParamString(resule, "code") == "200")
                        {
                            //客户编码
                            CustomerNumber = CommonService.GetJParamString(resule, "Number");
                            JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", CustomerNumber }
                                                                };

                            resule = CommonService.SubmitMethod(ctx, "BD_Customer", jobj.ToString());
                            if (CommonService.GetJParamString(resule, "code") == "200")
                            {
                                resule = CommonService.AuditMethod(ctx, "BD_Customer", jobj.ToString());
                                if (CommonService.GetJParamString(resule, "code") != "200")
                                {
                                    result["Message"] = CommonService.GetJParamString(resule, "msg");
                                }
                                else
                                {
                                    //创建商家
                                    string CreateStoresfiles = CommonService.CreateStoresfiles.Replace("区域", OrgNumber).Replace("客户", CustomerNumber).Replace("商家名称", CustomerName).Replace("用户账号", Name).Replace("销售员", SalerNumber);
                                    resule = CommonService.SaveMethod(ctx, "ora_Storesfiles", CreateStoresfiles);
                                    if (CommonService.GetJParamString(resule, "code") == "200")
                                    {
                                        //商家编码
                                        StoresfilesNumber = CommonService.GetJParamString(resule, "Number");
                                        jobj = new JObject
                                                                {
                                                                    { "Numbers", StoresfilesNumber }
                                                                };

                                        resule = CommonService.SubmitMethod(ctx, "ora_Storesfiles", jobj.ToString());
                                        if (CommonService.GetJParamString(resule, "code") == "200")
                                        {
                                            resule = CommonService.AuditMethod(ctx, "ora_Storesfiles", jobj.ToString());
                                            if (CommonService.GetJParamString(resule, "code") != "200")
                                            {
                                                result["Message"] = CommonService.GetJParamString(resule, "msg");
                                            }
                                        }
                                        else
                                        {
                                            result["Message"] = CommonService.GetJParamString(resule, "msg");
                                        }
                                    }
                                    else
                                    {
                                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                                    }
                                }
                            }
                            else
                            {
                                result["Message"] = CommonService.GetJParamString(resule, "msg");
                            }
                        }
                        else
                        {
                            result["Message"] = CommonService.GetJParamString(resule, "msg");
                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }
                }
                else
                {
                    result["Message"] = CommonService.GetJParamString(resule, "msg");
                }
                result["Result"] = true;
                result["Message"] = "用户注册成功！";
                Data.Add("UserNumber", Name); //编码
                Data.Add("CommonContactNumber", CommonContactNumber); //编码
                Data.Add("CustomerNumber", CustomerNumber); //编码
                Data.Add("StoresfilesNumber", StoresfilesNumber); //编码
                result["Data"] = Data;

            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("用户注册失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion



        //用户名称唯一查询
        internal string QueryUserName(Context ctx, string Name, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"select FNAME from T_SEC_user where FNAME = '{0}'", Name);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "用户名称唯一查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "用户名称唯一查询成功，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("用户名称唯一查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }


        //交易单号查询
        internal string QueryOrderNo(Context ctx, string OrderNo, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"select FBILLNO from ora_CompetitiveTransaction where FBILLNO = '{0}'", OrderNo);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "交易单号查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "交易单号查询成功，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("交易单号查询成功查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        #region 批量新增商品接口
        internal string AllAddMaterials(Context ctx, JObject jParams, JObject result)
        {
            result["Result"] = true;
            result["Message"] = "新增商品成功！";
            string json = "";
            string sql = "";
            string OrgNumber = "";
            string save = "";
            string Number = "";
            string Name = "";
            string Score = "";
            string Alcohols = "";
            string Note = "";
            string WineBase = "";
            string Size = "";
            string WineYear = "";
            string AuxUnit = "";
            JArray SubEntity = new JArray();
            try
            {
                JArray FBillEntry = JArray.Parse(jParams["Data"].ToString());
                foreach (JObject List in FBillEntry)
                {
                    json = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"true\"," +
                    "\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\"," +
                    "\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\"," +
                    "\"Model\":{\"FMATERIALID\":0,\"FCreateOrgId\":{\"FNumber\":\"区域编码\"},\"FUseOrgId\":{\"FNumber\":\"区域编码\"},\"FNumber\":\"商品编码\",\"FName\":\"商品名称\"," +
                    "\"FScore\":\"评分\",\"F_QUDE_CheckBox\":\"1\",\"FALCOHOLS\":{\"FNumber\":\"酒精度\"},\"F_ora_Memo\":\"备注\",\"FWineBase1\":{\"FNUMBER\":\"酒庄酒款编码\"},\"Fsize\":{\"FNumber\":\"规格\"}," +
                    "\"FWineYear1\":{\"FNumber\":\"年份\"},\"SubHeadEntity1\":{\"FAuxUnitID\":{\"FNumber\":\"包装\"}}}}";


                    OrgNumber = List["OrgNumber"].ToString();
                    Number = List["Number"].ToString();
                    Name = List["Name"].ToString();
                    Score = List["Score"].ToString();
                    Alcohols = List["Alcohols"].ToString();
                    Note = List["Note"].ToString();
                    WineBase = List["WineBase"].ToString();
                    Size = List["Size"].ToString();
                    WineYear = List["WineYear"].ToString();
                    AuxUnit = List["AuxUnit"].ToString();

                    save = json.Replace("区域编码", OrgNumber.ToString()).Replace("商品编码", Number.ToString()).Replace("商品名称", Name.ToString()).
                    Replace("评分", Score.ToString()).Replace("酒精度", Alcohols.ToString()).Replace("备注", Note.ToString()).Replace("酒庄酒款编码", WineBase.ToString()).
                    Replace("规格", Size.ToString()).Replace("年份", WineYear.ToString()).Replace("包装", AuxUnit.ToString());
                    JObject resule = CommonService.SaveMethod(ctx, "BD_MATERIAL", save);
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        Number = CommonService.GetJParamString(resule, "Number");
                        JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", Number }
                                                                };

                        resule = CommonService.SubmitMethod(ctx, "BD_MATERIAL", jobj.ToString());
                        if (CommonService.GetJParamString(resule, "code") == "200")
                        {
                            resule = CommonService.AuditMethod(ctx, "BD_MATERIAL", jobj.ToString());
                            if (CommonService.GetJParamString(resule, "code") != "200")
                            {
                                JObject Data = new JObject();
                                Data.Add("orgnumber", "");
                                Data.Add("orgname", "");
                                Data.Add("number", Number);
                                Data.Add("name", "");
                                Data.Add("winebase", "");
                                Data.Add("winebasename", "");
                                Data.Add("regions", "");
                                Data.Add("country", "");
                                Data.Add("style", "");
                                Data.Add("score", "");
                                Data.Add("note", "");
                                Data.Add("wineyear", "");
                                Data.Add("size", "");
                                Data.Add("alcohols", "");
                                Data.Add("storeunitid", "");
                                Data.Add("auxunitid", "");
                                Data.Add("xconvertnumerator", "");
                                SubEntity.Add(Data);
                            }
                            else
                            {
                                sql = string.Format(@"select  
                                    t7.FNUMBER as ORGNUMBER,
                                    t8.FNAME as ORGNAME,
                                    t1.FNUMBER as NUMBER,
                                    t2.FNAME as NAME,
                                    t3.FNUMBER as WINEBASE,
                                    t4.FNAME as WINEBASENAME,
                                    t3.FREGIONS AS REGIONS,
                                    t5.FDATAVALUE as COUNTRY,
                                    t6.FDATAVALUE as STYLE,
                                    t1.FSCORE as SCORE,
                                    t1.F_ORA_MEMO as NOTE,
                                    t9.FDATAVALUE as WINEYEAR,
                                    isnull(t10.FDATAVALUE, '') as SIZE,
                                    isnull(t11.FDATAVALUE, '') as ALCOHOLS,
                                    t14.FNAME as STOREUNITID,
                                    t16.FNAME as AUXUNITID,
                                    t17.FXCONVERTNUMERATOR as XCONVERTNUMERATOR
                                    from T_BD_MATERIAL t1
                                    inner
                                    join T_BD_MATERIAL_L t2 on t2.FMATERIALID = t1.FMATERIALID and t2.FLOCALEID = 2052
                                    left join ora_t_Cust100034 t3 on t3.FID = t1.FWINEBASE1
                                    left join ora_t_Cust100034_L t4 on t4.FID = t3.FID  and t4.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t5 on t5.FENTRYID = t3.FCOUNTRY and t5.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t6 on t6.FENTRYID = t3.FSTYLE and t6.FLOCALEID = 2052
                                    left join T_ORG_ORGANIZATIONS t7 on t7.FORGID = t1.FUSEORGID
                                    left join T_ORG_ORGANIZATIONS_L t8 on t8.FORGID = t7.FORGID  and t8.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t9 on t9.FENTRYID = t1.FWINEYEAR1 and t9.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t10 on t10.FENTRYID = t1.FSIZE and t10.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t11 on t11.FENTRYID = t1.FALCOHOLS and t11.FLOCALEID = 2052
                                    left join t_BD_MaterialStock t12 on t12.FMATERIALID = t1.FMATERIALID
                                    left join T_BD_UNIT t13 on t13.FUNITID = t12.FSTOREUNITID
                                    left join T_BD_UNIT_L t14 on t14.FUNITID = t13.FUNITID and t14.FLOCALEID = 2052
                                    left join T_BD_UNIT t15 on t15.FUNITID = t12.FAUXUNITID
                                    left join T_BD_UNITCONVERTRATE t17 ON t17.FUNITID = t15.FUNITID
                                    left join T_BD_UNIT_L t16 on t16.FUNITID = t15.FUNITID and t16.FLOCALEID = 2052
                                    
                                    where t1.FDOCUMENTSTATUS = 'C' AND  T1.FNUMBER ='{0}' AND T7.FNUMBER ='{1}'", Number, OrgNumber);
                                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                                if (Datas != null && Datas.Count > 0)
                                {
                                    JObject Data = new JObject();
                                    Data.Add("orgnumber", Datas.First()["ORGNUMBER"].ToString());
                                    Data.Add("orgname", Datas.First()["ORGNAME"].ToString());
                                    Data.Add("number", Datas.First()["NUMBER"].ToString());
                                    Data.Add("name", Datas.First()["NAME"].ToString());
                                    Data.Add("winebase", Datas.First()["WINEBASE"].ToString());
                                    Data.Add("winebasename", Datas.First()["WINEBASENAME"].ToString());
                                    Data.Add("regions", Datas.First()["REGIONS"].ToString());
                                    Data.Add("country", Datas.First()["COUNTRY"].ToString());
                                    Data.Add("style", Datas.First()["STYLE"].ToString());
                                    Data.Add("score", Datas.First()["SCORE"].ToString());
                                    Data.Add("note", Datas.First()["NOTE"].ToString());
                                    Data.Add("wineyear", Datas.First()["WINEYEAR"].ToString());
                                    Data.Add("size", Datas.First()["SIZE"].ToString());
                                    Data.Add("alcohols", Datas.First()["ALCOHOLS"].ToString());
                                    Data.Add("storeunitid", Datas.First()["STOREUNITID"].ToString());
                                    Data.Add("auxunitid", Datas.First()["AUXUNITID"].ToString());
                                    Data.Add("xconvertnumerator", Datas.First()["XCONVERTNUMERATOR"].ToString());
                                    SubEntity.Add(Data);
                                }
                            }
                        }
                        else
                        {
                            JObject Data = new JObject();
                            Data.Add("orgnumber", "");
                            Data.Add("orgname", "");
                            Data.Add("number", Number);
                            Data.Add("name", "");
                            Data.Add("winebase", "");
                            Data.Add("winebasename", "");
                            Data.Add("regions", "");
                            Data.Add("country", "");
                            Data.Add("style", "");
                            Data.Add("score", "");
                            Data.Add("note", "");
                            Data.Add("wineyear", "");
                            Data.Add("size", "");
                            Data.Add("alcohols", "");
                            Data.Add("storeunitid", "");
                            Data.Add("auxunitid", "");
                            Data.Add("xconvertnumerator", "");
                            SubEntity.Add(Data);
                        }
                    }
                    else
                    {
                        JObject Data = new JObject();
                        Data.Add("orgnumber", "");
                        Data.Add("orgname", "");
                        Data.Add("number", Number);
                        Data.Add("name", "");
                        Data.Add("winebase", "");
                        Data.Add("winebasename", "");
                        Data.Add("regions", "");
                        Data.Add("country", "");
                        Data.Add("style", "");
                        Data.Add("score", "");
                        Data.Add("note", "");
                        Data.Add("wineyear", "");
                        Data.Add("size", "");
                        Data.Add("alcohols", "");
                        Data.Add("storeunitid", "");
                        Data.Add("auxunitid", "");
                        Data.Add("xconvertnumerator", "");
                        SubEntity.Add(Data);
                    }
                }
                result["Data"] = SubEntity;
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("新增商品失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 新增商品接口
        internal string AddMaterials(Context ctx, string OrgNumber, string FNumber, string FName, string FScore, string FALCOHOLS, string FNote, string FWineBase1, string Fsize, string FWineYear1, string FAuxUnitID, JObject result)
        {
            result["Result"] = false;
            try
            {
                string json = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"true\"," +
                    "\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\"," +
                    "\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\"," +
                    "\"Model\":{\"FMATERIALID\":0,\"FCreateOrgId\":{\"FNumber\":\"区域编码\"},\"FUseOrgId\":{\"FNumber\":\"区域编码\"},\"FNumber\":\"商品编码\",\"FName\":\"商品名称\"," +
                    "\"FScore\":\"评分\",\"F_QUDE_CheckBox\":\"1\",\"FALCOHOLS\":{\"FNumber\":\"酒精度\"},\"F_ora_Memo\":\"备注\",\"FWineBase1\":{\"FNUMBER\":\"酒庄酒款编码\"},\"Fsize\":{\"FNumber\":\"规格\"}," +
                    "\"FWineYear1\":{\"FNumber\":\"年份\"},\"SubHeadEntity1\":{\"FAuxUnitID\":{\"FNumber\":\"包装\"}}}}";
                string save = json.Replace("区域编码", OrgNumber.ToString()).Replace("商品编码", FNumber.ToString()).Replace("商品名称", FName.ToString()).
                    Replace("评分", FScore.ToString()).Replace("酒精度", FALCOHOLS.ToString()).Replace("备注", FNote.ToString()).Replace("酒庄酒款编码", FWineBase1.ToString()).
                    Replace("规格", Fsize.ToString()).Replace("年份", FWineYear1.ToString()).Replace("包装", FAuxUnitID.ToString());
                JObject resule = CommonService.SaveMethod(ctx, "BD_MATERIAL", save);
                if (CommonService.GetJParamString(resule, "code") == "200")
                {
                    FNumber = CommonService.GetJParamString(resule, "Number");
                    JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", FNumber }
                                                                };

                    resule = CommonService.SubmitMethod(ctx, "BD_MATERIAL", jobj.ToString());
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        resule = CommonService.AuditMethod(ctx, "BD_MATERIAL", jobj.ToString());
                        if (CommonService.GetJParamString(resule, "code") != "200")
                        {
                            result["Message"] = CommonService.GetJParamString(resule, "msg");
                        }
                        else
                        {
                            string sql = string.Format(@"select  
                                    t7.FNUMBER as ORGNUMBER,
                                    t8.FNAME as ORGNAME,
                                    t1.FNUMBER as NUMBER,
                                    t2.FNAME as NAME,
                                    t3.FNUMBER as WINEBASE,
                                    t4.FNAME as WINEBASENAME,
                                    t3.FREGIONS AS REGIONS,
                                    t5.FDATAVALUE as COUNTRY,
                                    t6.FDATAVALUE as STYLE,
                                    t1.FSCORE as SCORE,
                                    t1.F_ORA_MEMO as NOTE,
                                    t9.FDATAVALUE as WINEYEAR,
                                    isnull(t10.FDATAVALUE, '') as SIZE,
                                    isnull(t11.FDATAVALUE, '') as ALCOHOLS,
                                    t14.FNAME as STOREUNITID,
                                    t16.FNAME as AUXUNITID,
                                    t17.FXCONVERTNUMERATOR as XCONVERTNUMERATOR
                                    from T_BD_MATERIAL t1
                                    inner
                                    join T_BD_MATERIAL_L t2 on t2.FMATERIALID = t1.FMATERIALID and t2.FLOCALEID = 2052
                                    left join ora_t_Cust100034 t3 on t3.FID = t1.FWINEBASE1
                                    left join ora_t_Cust100034_L t4 on t4.FID = t3.FID  and t4.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t5 on t5.FENTRYID = t3.FCOUNTRY and t5.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t6 on t6.FENTRYID = t3.FSTYLE and t6.FLOCALEID = 2052
                                    left join T_ORG_ORGANIZATIONS t7 on t7.FORGID = t1.FUSEORGID
                                    left join T_ORG_ORGANIZATIONS_L t8 on t8.FORGID = t7.FORGID  and t8.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t9 on t9.FENTRYID = t1.FWINEYEAR1 and t9.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t10 on t10.FENTRYID = t1.FSIZE and t10.FLOCALEID = 2052
                                    left join T_BAS_ASSISTANTDATAENTRY_L t11 on t11.FENTRYID = t1.FALCOHOLS and t11.FLOCALEID = 2052
                                    left join t_BD_MaterialStock t12 on t12.FMATERIALID = t1.FMATERIALID
                                    left join T_BD_UNIT t13 on t13.FUNITID = t12.FSTOREUNITID
                                    left join T_BD_UNIT_L t14 on t14.FUNITID = t13.FUNITID and t14.FLOCALEID = 2052
                                    left join T_BD_UNIT t15 on t15.FUNITID = t12.FAUXUNITID
                                    left join T_BD_UNITCONVERTRATE t17 ON t17.FUNITID = t15.FUNITID
                                    left join T_BD_UNIT_L t16 on t16.FUNITID = t15.FUNITID and t16.FLOCALEID = 2052
                                    
                                    where t1.FDOCUMENTSTATUS = 'C' AND  T1.FNUMBER ='{0}' AND T7.FNUMBER ='{1}'", FNumber, OrgNumber);
                            var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                            if (Datas != null && Datas.Count > 0)
                            {
                                result["Result"] = true;
                                result["Message"] = "新增商品成功！";
                                JObject Data = new JObject();
                                result["Data"] = JArray.FromObject(Datas);
                            }
                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }
                }
                else
                {
                    result["Message"] = CommonService.GetJParamString(resule, "msg");
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("新增商品失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 修改商品接口
        internal string UpdateMaterials(Context ctx, string OrgNumber, string FNumber, string FName, string FScore, string FALCOHOLS, string FNote, string FWineBase1, string Fsize, string FWineYear1, string FAuxUnitID, JObject result)
        {

            result["Result"] = false;
            try
            {
                string sql = string.Format(@"select T.FMATERIALID AS FMATERIALID from T_BD_MATERIAL T 
                                                INNER JOIN T_ORG_ORGANIZATIONS T1 ON T1.FORGID = T.FUSEORGID
                                                where T.FNUMBER = '{0}' AND T1.FNUMBER = '{1}'", FNumber, OrgNumber);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    string json = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"true\"," +
                   "\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\"," +
                   "\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\"," +
                   "\"Model\":{\"FMATERIALID\":商品ID,\"FName\":\"商品名称\"," +
                   "\"FScore\":\"评分\",\"FALCOHOLS\":{\"FNumber\":\"酒精度\"},\"F_ora_Memo\":\"备注\",\"FWineBase1\":{\"FNUMBER\":\"酒庄酒款编码\"},\"Fsize\":{\"FNumber\":\"规格\"}," +
                   "\"FWineYear1\":{\"FNumber\":\"年份\"},\"SubHeadEntity1\":{\"FAuxUnitID\":{\"FNumber\":\"包装\"}}}}";
                    string save = json.Replace("商品ID", Convert.ToString(Datas.First()["FMATERIALID"])).Replace("商品名称", FName.ToString()).
                        Replace("评分", FScore.ToString()).Replace("酒精度", FALCOHOLS.ToString()).Replace("备注", FNote.ToString()).Replace("酒庄酒款编码", FWineBase1.ToString()).
                        Replace("规格", Fsize.ToString()).Replace("年份", FWineYear1.ToString()).Replace("包装", FAuxUnitID.ToString());
                    JObject resule = CommonService.SaveMethod(ctx, "BD_MATERIAL", save);
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        FNumber = CommonService.GetJParamString(resule, "Number");
                        result["Result"] = true;
                        result["Message"] = "修改商品成功！";
                        JObject Data = new JObject();
                        Data.Add("Number", FNumber); //编码
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = string.Format("商品编码：{0}返回查询结果为空！", FNumber);
                }

            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("商品修改失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 新增酒款接口
        internal string AddWineryTreasury(Context ctx, string FNumber, string FDate, string FName, string FEnglish, string FCountry, string FStyle, string FREGIONS, string F_ora_MulLangText, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"/*dialect*/select FID from ora_t_Cust100034 where FNUMBER = '{0}'", FNumber);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    string json = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"true\"," +
                    "\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\"," +
                    "\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"Model\":{\"FNumber\":\"编码\",\"FID\":主键,\"FCreateDate\":\"日期\"," +
                    "\"FName\":\"酒款名称\",\"FEnglish\":\"英文名\",\"FCountry\":{\"FNumber\":\"国家\"},\"FStyle\":{\"FNumber\":\"类型\"},\"FREGIONS\":\"产区\"," +
                    "\"F_ora_MulLangText\":\"中文名\"}}";
                    string save = json.Replace("编码", FNumber.ToString()).Replace("日期", FDate.ToString()).Replace("酒款名称", FName.ToString()).Replace("主键", Datas.First()["FID"].ToString()).
                        Replace("英文名", FEnglish.ToString()).Replace("国家", FCountry.ToString()).Replace("类型", FStyle.ToString()).Replace("产区", FREGIONS.ToString()).
                        Replace("中文名", F_ora_MulLangText.ToString());
                    JObject resule = CommonService.SaveMethod(ctx, "ora_WineryTreasury", save);
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        FNumber = CommonService.GetJParamString(resule, "Number");
                        JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", FNumber }
                                                                };
                        sql = string.Format(@"/*dialect*/select
                                                    t.FNUMBER as FNUMBER,
                                                    t1.FNAME as FNAME,
                                                    t1.F_ORA_MULLANGTEXT as F_ORA_MULLANGTEXT,
                                                    t.FENGLISH as FENGLISH,
                                                    t.FREGIONS as FREGIONS,
                                                    t2.FDATAVALUE as FCOUNTRY,
                                                    t3.FDATAVALUE as FSTYLE,
                                                    t.FDOCUMENTSTATUS as FDOCUMENTSTATUS
                                                    from
                                                    ora_t_Cust100034 t
                                                    inner
                                                    join ora_t_Cust100034_L t1 on t1.FID = t.FID and t1.FLocaleID = 2052
                                                    left join T_BAS_ASSISTANTDATAENTRY_L t2 on t2.FENTRYID = t.FCOUNTRY and t2.FLOCALEID = 2052
                                                    left join T_BAS_ASSISTANTDATAENTRY_L t3 on t3.FENTRYID = t.FSTYLE and t3.FLOCALEID = 2052
                                                    where  t.FNUMBER = '{0}'", FNumber);
                        Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                        if (Datas != null && Datas.Count > 0)
                        {
                            result["Result"] = true;
                            result["Message"] = "修改酒款成功！";
                            result["Data"] = JArray.FromObject(Datas);
                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }

                }
                else
                {
                    string json = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"true\"," +
                    "\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\"," +
                    "\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"Model\":{\"FNumber\":\"编码\",\"FID\":0,\"FCreateDate\":\"日期\"," +
                    "\"FName\":\"酒款名称\",\"FEnglish\":\"英文名\",\"FCountry\":{\"FNumber\":\"国家\"},\"FStyle\":{\"FNumber\":\"类型\"},\"FREGIONS\":\"产区\"," +
                    "\"F_ora_MulLangText\":\"中文名\"}}";
                    string save = json.Replace("编码", FNumber.ToString()).Replace("日期", FDate.ToString()).Replace("酒款名称", FName.ToString()).
                        Replace("英文名", FEnglish.ToString()).Replace("国家", FCountry.ToString()).Replace("类型", FStyle.ToString()).Replace("产区", FREGIONS.ToString()).
                        Replace("中文名", F_ora_MulLangText.ToString());
                    JObject resule = CommonService.SaveMethod(ctx, "ora_WineryTreasury", save);
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        FNumber = CommonService.GetJParamString(resule, "Number");
                        JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", FNumber }
                                                                };
                        sql = string.Format(@"/*dialect*/select
                                                    t.FNUMBER as FNUMBER,
                                                    t1.FNAME as FNAME,
                                                    t1.F_ORA_MULLANGTEXT as F_ORA_MULLANGTEXT,
                                                    t.FENGLISH as FENGLISH,
                                                    t.FREGIONS as FREGIONS,
                                                    t2.FDATAVALUE as FCOUNTRY,
                                                    t3.FDATAVALUE as FSTYLE,
                                                    t.FDOCUMENTSTATUS as FDOCUMENTSTATUS
                                                    from
                                                    ora_t_Cust100034 t
                                                    inner
                                                    join ora_t_Cust100034_L t1 on t1.FID = t.FID and t1.FLocaleID = 2052
                                                    left join T_BAS_ASSISTANTDATAENTRY_L t2 on t2.FENTRYID = t.FCOUNTRY and t2.FLOCALEID = 2052
                                                    left join T_BAS_ASSISTANTDATAENTRY_L t3 on t3.FENTRYID = t.FSTYLE and t3.FLOCALEID = 2052
                                                    where  t.FNUMBER = '{0}'", FNumber);
                        Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                        if (Datas != null && Datas.Count > 0)
                        {
                            result["Result"] = true;
                            result["Message"] = "新增酒款成功！";
                            result["Data"] = JArray.FromObject(Datas);
                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }

                }

            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("新增商品失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion



        #region 新增国家红酒类型接口
        internal string AddAssistantData(Context ctx, string FNumber, string FName, string FType, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"/*dialect*/select top 1 t.FNUMBER as Number,t1.FDATAVALUE as Name,t.FENTRYID as FENTRYID from T_BAS_ASSISTANTDATAENTRY t 
                                                                        inner join T_BAS_ASSISTANTDATAENTRY_L t1 on t1.FENTRYID = t.FENTRYID
                                                                        where (t.FNUMBER = '{0}' or t1.FDATAVALUE = '{1}') and (t.FID = '61bab0851e110f' OR t.FID = '8a6e30f0-2c26-4639-aff5-76749daa355e')", FNumber, FName);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    string json = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"true\"," +
                    "\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\"," +
                    "\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",\"Model\":{\"FEntryID\":\"分录\",\"FNumber\":\"编码\"," +
                    "\"FDataValue\":\"名称\",\"FId\":{\"FNumber\":\"类型\"}}}";
                    string save = json.Replace("编码", FNumber.ToString()).Replace("名称", FName.ToString()).Replace("分录", Datas.First()["FENTRYID"].ToString()).
                        Replace("类型", FType.ToString());
                    JObject resule = CommonService.SaveMethod(ctx, "BOS_ASSISTANTDATA_DETAIL", save);
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        FNumber = CommonService.GetJParamString(resule, "Number");
                        JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", FNumber }
                                                                };
                        sql = string.Format(@"/*dialect*/select top 1 t.FNUMBER as Number,t1.FDATAVALUE as Name from T_BAS_ASSISTANTDATAENTRY t 
                                                                        inner join T_BAS_ASSISTANTDATAENTRY_L t1 on t1.FENTRYID = t.FENTRYID
                                                                        where (t.FNUMBER = '{0}' or t1.FDATAVALUE = '{1}') and (t.FID = '61bab0851e110f' OR t.FID = '8a6e30f0-2c26-4639-aff5-76749daa355e')", FNumber, FName);
                        Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                        if (Datas != null && Datas.Count > 0)
                        {
                            result["Result"] = true;
                            result["Message"] = "修改国家红酒类型成功！";
                            result["Data"] = JArray.FromObject(Datas);
                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }
                }
                else
                {
                    string json = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"true\"," +
                    "\"IsEntryBatchFill\":\"true\",\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\"," +
                    "\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",\"Model\":{\"FEntryID\":0,\"FNumber\":\"编码\"," +
                    "\"FDataValue\":\"名称\",\"FId\":{\"FNumber\":\"类型\"}}}";
                    string save = json.Replace("编码", FNumber.ToString()).Replace("名称", FName.ToString()).
                        Replace("类型", FType.ToString());
                    JObject resule = CommonService.SaveMethod(ctx, "BOS_ASSISTANTDATA_DETAIL", save);
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        FNumber = CommonService.GetJParamString(resule, "Number");
                        JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", FNumber }
                                                                };
                        resule = CommonService.SubmitMethod(ctx, "BOS_ASSISTANTDATA_DETAIL", jobj.ToString());
                        if (CommonService.GetJParamString(resule, "code") == "200")
                        {
                            resule = CommonService.AuditMethod(ctx, "BOS_ASSISTANTDATA_DETAIL", jobj.ToString());
                            if (CommonService.GetJParamString(resule, "code") != "200")
                            {
                                result["Message"] = CommonService.GetJParamString(resule, "msg");
                            }
                            else
                            {
                                sql = string.Format(@"/*dialect*/select top 1 t.FNUMBER as Number,t1.FDATAVALUE as Name from T_BAS_ASSISTANTDATAENTRY t 
                                                                        inner join T_BAS_ASSISTANTDATAENTRY_L t1 on t1.FENTRYID = t.FENTRYID
                                                                        where (t.FNUMBER = '{0}' or t1.FDATAVALUE = '{1}') and (t.FID = '61bab0851e110f' OR t.FID = '8a6e30f0-2c26-4639-aff5-76749daa355e')", FNumber, FName);
                                Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                                if (Datas != null && Datas.Count > 0)
                                {
                                    result["Result"] = true;
                                    result["Message"] = "新增国家红酒类型成功！";
                                    result["Data"] = JArray.FromObject(Datas);
                                }
                            }
                        }
                        else
                        {
                            result["Message"] = CommonService.GetJParamString(resule, "msg");
                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }
                }

            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("新增国家红酒类型成功失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        //公仓出库列表查询(其他出库)
        internal string QueryMisdeliveryList(Context ctx, string Mobile, string OrgNumber, string Status, string BillNo, string BDate, string EDate, int iPageSize, int iPageNum, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                if (!string.IsNullOrWhiteSpace(BillNo))
                {
                    BillNo = string.Format("AND  t.FBILLNO = '{0}'", BillNo);
                }
                if (!string.IsNullOrWhiteSpace(BDate))
                {
                    BDate = string.Format("AND CONVERT(varchar(100), t.FDATE, 120) >= '{0}'", BDate);
                }
                if (!string.IsNullOrWhiteSpace(EDate))
                {
                    EDate = string.Format("AND CONVERT(varchar(100), t.FDATE, 120) <= '{0}'", EDate);
                }
                if (Status == "A" || Status == "D")
                {
                    sql = string.Format(@"/*dialect*/select * from (
                                                select 
                                                ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.FDATE, 120) DESC) AS FIDENTITYID,count(1) over() as TotalCount,
                                                t.FBILLNO as BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                isnull(CONVERT(varchar(100), t.F_QUDE_DATE, 120),'')  as DeliveredDate,
                                                isnull(CONVERT(varchar(100), t.FAPPROVEDATE, 120),'')  as DeliveryDate,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                t4.FNAME as Customer,
                                                t6.FNAME as Owner,
                                                F_QUDE_QTY as AllQty,
                                                F_QUDE_AMOUNT as AllAmount,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核'
                                                when t.FDOCUMENTSTATUS = 'D' then '重新审核' 
                                                when t.FDOCUMENTSTATUS = 'B' then '审核中' 
                                                when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
                                                t12.FSYSMBOL as SysMbol,
                                                t.F_QUDE_REMARKS as Note,
                                                t.FNOTE as Notes
                                                from T_STK_MISDELIVERY t 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FSTOCKORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052 
                                                inner join T_BD_CUSTOMER t3 on t3.FCUSTID = t.FCUSTID
                                                inner join T_BD_CUSTOMER_L t4 on t4.FCUSTID = t3.FCUSTID and t4.FLOCALEID = 2052
                                                inner join T_BD_CUSTOMER t5 on t5.FCUSTID = FOWNERID
                                                inner join T_BD_CUSTOMER_L t6 on t6.FCUSTID = t5.FCUSTID and t6.FLOCALEID = 2052
                                                inner JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t.FSTOCKORGID
                                                inner JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                inner JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                inner JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
                                                inner join 
                                                (select t1.FID as FID from T_SEC_user t
                                                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
                                                where (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}')
                                                )tf on tf.FID = t.F_QUDE_MERCHANT
                                                where t1.FNUMBER = '{1}' and (t.FDOCUMENTSTATUS = 'D' OR t.FDOCUMENTSTATUS = 'A') {4} {5} {6} ) t
                                                where  t.FIDENTITYID between {2} and {3}", Mobile, OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, BillNo, BDate, EDate);
                }
                else
                {
                    sql = string.Format(@"/*dialect*/select * from (
                                                select 
                                               ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.FDATE, 120) DESC) AS FIDENTITYID,count(1) over() as TotalCount,
                                                t.FBILLNO as BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                isnull(CONVERT(varchar(100), t.F_QUDE_DATE, 120),'')  as DeliveredDate,
                                                isnull(CONVERT(varchar(100), t.FAPPROVEDATE, 120),'')  as DeliveryDate,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                t4.FNAME as Customer,
                                                t6.FNAME as Owner,
                                                F_QUDE_QTY as AllQty,
                                                F_QUDE_AMOUNT as AllAmount,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核'
                                                when t.FDOCUMENTSTATUS = 'D' then '重新审核' 
                                                when t.FDOCUMENTSTATUS = 'B' then '审核中' 
                                                when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
                                                t12.FSYSMBOL as SysMbol,
                                                t.F_QUDE_REMARKS as Note,
                                                t.FNOTE as Notes
                                                from T_STK_MISDELIVERY t 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FSTOCKORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052 
                                                inner join T_BD_CUSTOMER t3 on t3.FCUSTID = t.FCUSTID
                                                inner join T_BD_CUSTOMER_L t4 on t4.FCUSTID = t3.FCUSTID and t4.FLOCALEID = 2052
                                                inner join T_BD_CUSTOMER t5 on t5.FCUSTID = FOWNERID
                                                inner join T_BD_CUSTOMER_L t6 on t6.FCUSTID = t5.FCUSTID and t6.FLOCALEID = 2052
                                                inner JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t.FSTOCKORGID
                                                inner JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                inner JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                inner JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
                                                inner join 
                                                (select t1.FID as FID from T_SEC_user t
                                                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
                                                where (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}')
                                                )tf on tf.FID = t.F_QUDE_MERCHANT
                                                where t1.FNUMBER = '{1}' and t.FDOCUMENTSTATUS = '{4}' {5} {6} {7}) t
                                                where  t.FIDENTITYID between {2} and {3}", Mobile, OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, Status, BillNo, BDate, EDate);
                }

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "公仓出库列表查询成功！";
                    result["TotalCount"] = Convert.ToInt64(Datas.First()["TotalCount"]);
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "公仓出库列表查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("公仓出库列表失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //销售出库详情查询(其他出库)
        internal string QueryMisdelivery(Context ctx, string BillNo, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                sql = string.Format(@"/*dialect*/select 
                                               t.FBILLNO as BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                isnull(CONVERT(varchar(100), t.F_QUDE_DATE, 120),'')  as DeliveredDate,
                                                isnull(CONVERT(varchar(100), t.FAPPROVEDATE, 120),'')  as DeliveryDate,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                t4.FNAME as Customer,
                                                t6.FNAME as Owner,
                                                F_QUDE_QTY as AllQty,
                                                F_QUDE_AMOUNT as AllAmount,
                                                FLRAMOUNT as AllProfit,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核'
                                                when t.FDOCUMENTSTATUS = 'D' then '重新审核' 
                                                when t.FDOCUMENTSTATUS = 'B' then '审核中' 
                                                when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
                                                t12.FSYSMBOL as SysMbol,
                                                t.F_QUDE_REMARKS as Note,
                                                t.FNOTE as Notes
                                                from T_STK_MISDELIVERY t 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FSTOCKORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052 
                                                inner join T_BD_CUSTOMER t3 on t3.FCUSTID = t.FCUSTID
                                                inner join T_BD_CUSTOMER_L t4 on t4.FCUSTID = t3.FCUSTID and t4.FLOCALEID = 2052
                                                inner join T_BD_CUSTOMER t5 on t5.FCUSTID = FOWNERID
                                                inner join T_BD_CUSTOMER_L t6 on t6.FCUSTID = t5.FCUSTID and t6.FLOCALEID = 2052
                                                inner JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t.FSTOCKORGID
                                                inner JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                inner JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                inner JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
												where t.FBILLNO = '{0}'", BillNo);

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    JObject jVipData = JObject.FromObject(Datas.First());

                    JObject Entry = new JObject();
                    Entry.Add("Result", false);
                    Entry.Add("Message", "");
                    Entry.Add("Data", string.Empty);

                    this.QueryMisdeliveryEntry(ctx, BillNo, Entry);
                    jVipData.Add("Entry", Entry["Data"]);

                    result["Result"] = true;
                    result["Message"] = "销售出库详情查询成功！";
                    result["Data"] = jVipData;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "销售出库详情查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("销售出库详情失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        #region 销售出库详情(其他出库)明细
        internal string QueryMisdeliveryEntry(Context ctx, string BillNo, JObject result)
        {
            try
            {
                result["Result"] = false;
                string sql = string.Format(@"/*dialect*/select 
                                                t2.FNUMBER as Material,
												t3.FNAME as MaterialName,
												t5.FNAME as StockName,
												t6.FNAME as StockStatus,
												t1.FQTY as Qty,
												t1.FPRICE as SalePrcice,
												t1.F_ora_JCostPrice as CostPrice,
												t1.FALAmount as ALAmount,
												t1.FQTY * t1.FPRICE as AllAmount,
												t1.FNOTE as Note,
												t1.FKQTY as Kqty
                                                from T_STK_MISDELIVERY t 
                                                inner join T_STK_MISDELIVERYENTRY t1 on t1.FID = t.FID
												inner join T_BD_MATERIAL t2 on t2.FMATERIALID = t1.FMATERIALID
												inner join T_BD_MATERIAL_L t3 on t3.FMATERIALID = t2.FMATERIALID and t3.FLOCALEID = 2052
												inner join T_BD_STOCK t4 on t4.FSTOCKID = t1.FStockId
												inner join T_BD_STOCK_L t5 on t5.FSTOCKID = t4.FStockId and t5.FLOCALEID = 2052
												inner join T_BD_STOCKSTATUS_L t6 on t6.FSTOCKSTATUSID = t1.FSTOCKSTATUSID and t6.FLOCALEID = 2052
												where t.FBILLNO = '{0}'", BillNo);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "其他出库详情成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "其他出库详情完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("其他出库详情失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        //公仓入库列表查询(其他入库)
        internal string QueryMiscellaneousList(Context ctx, string Mobile, string OrgNumber, string Status, string BillNo, string BDate, string EDate, int iPageSize, int iPageNum, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                if (!string.IsNullOrWhiteSpace(BillNo))
                {
                    BillNo = string.Format("AND  t.FBILLNO = '{0}'", BillNo);
                }
                if (!string.IsNullOrWhiteSpace(BDate))
                {
                    BDate = string.Format("AND CONVERT(varchar(100), t.FDATE, 120) >= '{0}'", BDate);
                }
                if (!string.IsNullOrWhiteSpace(EDate))
                {
                    EDate = string.Format("AND CONVERT(varchar(100), t.FDATE, 120) <= '{0}'", EDate);
                }
                if (Status == "A" || Status == "D")
                {
                    sql = string.Format(@"/*dialect*/select * from (
                                                select 
                                                ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.FDATE, 120) DESC) AS FIDENTITYID,count(1) over() as TotalCount,
                                                t.FBILLNO as BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
												isnull(CONVERT(varchar(100), t.F_QUDE_DATE, 120),'')  as ArrivalDate,
												isnull(CONVERT(varchar(100), t.FAPPROVEDATE, 120),'')  as WarehousingDate,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                t4.FNAME as Supplier,
                                                t6.FNAME as Customer,
												t.F_QUDE_QTY as AllQty,
												t.F_QUDE_AMOUNT as AllAmount,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核'
                                                when t.FDOCUMENTSTATUS = 'D' then '重新审核' 
                                                when t.FDOCUMENTSTATUS = 'B' then '审核中' 
                                                when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
                                                t12.FSYSMBOL as SysMbol,
                                                t.F_QUDE_REMARKS as Note
                                                from T_STK_MISCELLANEOUS t 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FSTOCKORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052 
                                                inner join T_BD_SUPPLIER t3 on t3.FSUPPLIERID = t.FSUPPLIERID
                                                inner join T_BD_SUPPLIER_L t4 on t4.FSUPPLIERID = t3.FSUPPLIERID and t4.FLOCALEID = 2052
                                                inner join T_BD_CUSTOMER t5 on t5.FCUSTID = FOWNERID
                                                inner join T_BD_CUSTOMER_L t6 on t6.FCUSTID = t5.FCUSTID and t6.FLOCALEID = 2052
                                                inner JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t.FSTOCKORGID
                                                inner JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                inner JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                inner JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
                                                inner join 
                                                (select t1.FID as FID from T_SEC_user t
                                                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
                                                where (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}')
                                                )tf on tf.FID = t.F_QUDE_MERCHANT
                                                where t1.FNUMBER = '{1}' and (t.FDOCUMENTSTATUS = 'D' OR t.FDOCUMENTSTATUS = 'A') {4} {5} {6} ) t
                                                where  t.FIDENTITYID between {2} and {3}", Mobile, OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, BillNo, BDate, EDate);
                }
                else
                {
                    sql = string.Format(@"/*dialect*/select * from (
                                                select 
                                                ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.FDATE, 120) DESC) AS FIDENTITYID,count(1) over() as TotalCount,
                                                t.FBILLNO as BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
												isnull(CONVERT(varchar(100), t.F_QUDE_DATE, 120),'')  as ArrivalDate,
												isnull(CONVERT(varchar(100), t.FAPPROVEDATE, 120),'')  as WarehousingDate,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                t4.FNAME as Supplier,
                                                t6.FNAME as Customer,
												t.F_QUDE_QTY as AllQty,
												t.F_QUDE_AMOUNT as AllAmount,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核'
                                                when t.FDOCUMENTSTATUS = 'D' then '重新审核' 
                                                when t.FDOCUMENTSTATUS = 'B' then '审核中' 
                                                when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
                                                t12.FSYSMBOL as SysMbol,
                                                t.F_QUDE_REMARKS as Note
                                                from T_STK_MISCELLANEOUS t 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FSTOCKORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052 
                                                inner join T_BD_SUPPLIER t3 on t3.FSUPPLIERID = t.FSUPPLIERID
                                                inner join T_BD_SUPPLIER_L t4 on t4.FSUPPLIERID = t3.FSUPPLIERID and t4.FLOCALEID = 2052
                                                inner join T_BD_CUSTOMER t5 on t5.FCUSTID = FOWNERID
                                                inner join T_BD_CUSTOMER_L t6 on t6.FCUSTID = t5.FCUSTID and t6.FLOCALEID = 2052
                                                inner JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t.FSTOCKORGID
                                                inner JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                inner JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                inner JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
                                                inner join 
                                                (select t1.FID as FID from T_SEC_user t
                                                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
                                                where ( REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}')
                                                )tf on tf.FID = t.F_QUDE_MERCHANT
                                                where t1.FNUMBER = '{1}' and t.FDOCUMENTSTATUS = '{4}' {5} {6} {7}) t
                                                where  t.FIDENTITYID between {2} and {3}", Mobile, OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, Status, BillNo, BDate, EDate);
                }

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "公仓入库列表查询成功！";
                    result["TotalCount"] = Convert.ToInt64(Datas.First()["TotalCount"]);
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "公仓入库列表查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("公仓入库列表查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //公仓入库详情查询(其他入库)
        internal string QueryMiscellaneous(Context ctx, string BillNo, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                sql = string.Format(@"/*dialect*/ select 
                                               t.FBILLNO as BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                isnull(CONVERT(varchar(100), t.F_QUDE_DATE, 120),'')  as ArrivalDate,
                                                isnull(CONVERT(varchar(100), t.FAPPROVEDATE, 120),'')  as WarehousingDate,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                t4.FNAME as Supplier,
                                                t6.FNAME as Customer,
                                                t.F_QUDE_QTY as AllQty,
                                                t.F_QUDE_AMOUNT as AllAmount,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核'
                                                when t.FDOCUMENTSTATUS = 'D' then '重新审核' 
                                                when t.FDOCUMENTSTATUS = 'B' then '审核中' 
                                                when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
                                                t12.FSYSMBOL as SysMbol,
                                                t.F_QUDE_REMARKS as Note,
                                                t.FNOTE as Notes
                                                from T_STK_MISCELLANEOUS t 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FSTOCKORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052 
                                                inner join T_BD_SUPPLIER t3 on t3.FSUPPLIERID = t.FSUPPLIERID
                                                inner join T_BD_SUPPLIER_L t4 on t4.FSUPPLIERID = t3.FSUPPLIERID and t4.FLOCALEID = 2052
                                                inner join T_BD_CUSTOMER t5 on t5.FCUSTID = FOWNERID
                                                inner join T_BD_CUSTOMER_L t6 on t6.FCUSTID = t5.FCUSTID and t6.FLOCALEID = 2052
                                                inner JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t.FSTOCKORGID
                                                inner JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                inner JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                inner JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
												where t.FBILLNO = '{0}'", BillNo);

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    JObject jVipData = JObject.FromObject(Datas.First());

                    JObject Entry = new JObject();
                    Entry.Add("Result", false);
                    Entry.Add("Message", "");
                    Entry.Add("Data", string.Empty);

                    this.QueryMiscellaneousEntry(ctx, BillNo, Entry);
                    jVipData.Add("Entry", Entry["Data"]);

                    result["Result"] = true;
                    result["Message"] = "公仓入库详情查询成功！";
                    result["Data"] = jVipData;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "公仓入库详情查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("公仓入库详情失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        #region 公仓入库详情(其他入库)明细
        internal string QueryMiscellaneousEntry(Context ctx, string BillNo, JObject result)
        {
            try
            {
                result["Result"] = false;
                string sql = string.Format(@"/*dialect*/select 
                                                t2.FNUMBER as Material,
												t3.FNAME as MaterialName,
												t5.FNAME as StockName,
												t6.FNAME as StockStatus,
												t1.FQTY as Qty,
												t1.FPRICE as CostPrice,
												t1.F_ORA_WHOLESALEPRICE as WholeSalePrice,
												t1.F_ora_GroupPrice as GroupPrice,
												t1.FALLAMOUNT as AllAmount,
												t1.FNOTE as Note
                                                from T_STK_MISCELLANEOUS t 
                                                inner join T_STK_MISCELLANEOUSENTRY t1 on t1.FID = t.FID
												inner join T_BD_MATERIAL t2 on t2.FMATERIALID = t1.FMATERIALID
												inner join T_BD_MATERIAL_L t3 on t3.FMATERIALID = t2.FMATERIALID and t3.FLOCALEID = 2052
												inner join T_BD_STOCK t4 on t4.FSTOCKID = t1.FSTOCKID
												inner join T_BD_STOCK_L t5 on t5.FSTOCKID = t4.FStockId and t5.FLOCALEID = 2052
												inner join T_BD_STOCKSTATUS_L t6 on t6.FSTOCKSTATUSID = t1.FSTOCKSTATUSID and t6.FLOCALEID = 2052
												where t.FBILLNO = '{0}'", BillNo);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "公仓入库详情成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "公仓入库详情完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("公仓入库详情失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        //竞价采购入库列表查询
        internal string QueryInStockList(Context ctx, string Mobile, string OrgNumber, string Status, string BillNo, string BDate, string EDate, int iPageSize, int iPageNum, JObject result)
        {
            result["Result"] = false;
            try
            {
                if (!string.IsNullOrWhiteSpace(BillNo))
                {
                    BillNo = string.Format("AND t.FBILLNO = '{0}'", BillNo);
                }
                if (!string.IsNullOrWhiteSpace(BDate))
                {
                    BDate = string.Format("AND CONVERT(varchar(100), t.FDATE, 120) >= '{0}'", BDate);
                }
                if (!string.IsNullOrWhiteSpace(EDate))
                {
                    EDate = string.Format("AND CONVERT(varchar(100), t.FDATE, 120) <= '{0}'", EDate);
                }
                string sql = "";
                if (Status == "A" || Status == "D")
                {
                    sql = string.Format(@"/*dialect*/select * from (
                                                SELECT 
                                                ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.FDATE, 120) DESC) AS FIDENTITYID,
                                                T.FBILLNO AS BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                isnull(t4.FNAME,0) as Supplier,
                                                isnull(t6.FNAME,0) as PurchaserId,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核' when t.FDOCUMENTSTATUS = 'D' then '重新审核' when t.FDOCUMENTSTATUS = 'B' then '审核中' when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status
                                                FROM t_STK_InStock T 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FPURCHASEORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052
                                                left join T_BD_SUPPLIER t3 on t3.FSUPPLIERID = t.FSUPPLIERID
                                                left join T_BD_SUPPLIER_L t4 on t4.FSUPPLIERID = t3.FSUPPLIERID and t4.FLOCALEID = 2052
                                                left join V_BD_BUYER t5 on t5.fid = t.FPURCHASERID 
                                                left join V_BD_BUYER_L t6 on t6.fid = t5.fid  and t6.FLOCALEID = 2052
                                                left join t_STK_InStockFin t7 on t7.FID = t.FID
                                                inner join 
                                                (select t1.FID as FID from T_SEC_user t
                                                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
                                                where (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}')
                                                )tf on tf.FID = t.F_QUDE_MERCHANT
                                                where t1.FNUMBER = '{1}'  and (t.FDOCUMENTSTATUS = 'D' OR t.FDOCUMENTSTATUS = 'A')  {4} {5} {6}  ) t
                                                where  t.FIDENTITYID between {2} and {3}", Mobile, OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, BillNo, BDate, EDate);
                }
                else
                {
                    sql = string.Format(@"/*dialect*/select * from (
                                                SELECT 
                                                ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.FDATE, 120) DESC) AS FIDENTITYID,
                                                T.FBILLNO AS BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                isnull(t4.FNAME,0) as Supplier,
                                                isnull(t6.FNAME,0) as PurchaserId,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核' when t.FDOCUMENTSTATUS = 'D' then '重新审核' when t.FDOCUMENTSTATUS = 'B' then '审核中' when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status
                                                FROM t_STK_InStock T 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FPURCHASEORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052
                                                left join T_BD_SUPPLIER t3 on t3.FSUPPLIERID = t.FSUPPLIERID
                                                left join T_BD_SUPPLIER_L t4 on t4.FSUPPLIERID = t3.FSUPPLIERID and t4.FLOCALEID = 2052
                                                left join V_BD_BUYER t5 on t5.fid = t.FPURCHASERID 
                                                left join V_BD_BUYER_L t6 on t6.fid = t5.fid  and t6.FLOCALEID = 2052
                                                left join t_STK_InStockFin t7 on t7.FID = t.FID
                                                inner join 
                                                (select t1.FID as FID from T_SEC_user t
                                                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
                                                where (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}')
                                                )tf on tf.FID = t.F_QUDE_MERCHANT
                                                where t1.FNUMBER = '{1}'and t.FDOCUMENTSTATUS = '{4}' {5} {6} {7}) t
                                                where  t.FIDENTITYID between {2} and {3}", Mobile, OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, Status, BillNo, BDate, EDate);
                }

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "竞价采购入库列表查询成功！";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价采购入库列表查询成功，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价采购入库列表查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //竞价采购入库详情查询(采购入库)
        internal string QueryInStock(Context ctx, string BillNo, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                sql = string.Format(@"/*dialect*/ SELECT 
                                                T.FBILLNO AS BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                isnull(t4.FNAME,0) as Supplier,
                                                isnull(t6.FNAME,0) as PurchaserId,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核' when t.FDOCUMENTSTATUS = 'D' then '重新审核' when t.FDOCUMENTSTATUS = 'B' then '审核中' when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status
                                                FROM t_STK_InStock T 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FPURCHASEORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052
                                                left join T_BD_SUPPLIER t3 on t3.FSUPPLIERID = t.FSUPPLIERID
                                                left join T_BD_SUPPLIER_L t4 on t4.FSUPPLIERID = t3.FSUPPLIERID and t4.FLOCALEID = 2052
                                                left join V_BD_BUYER t5 on t5.fid = t.FPURCHASERID 
                                                left join V_BD_BUYER_L t6 on t6.fid = t5.fid  and t6.FLOCALEID = 2052
                                                left join t_STK_InStockFin t7 on t7.FID = t.FID
												where t.FBILLNO = '{0}'", BillNo);

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    JObject jVipData = JObject.FromObject(Datas.First());

                    JObject Entry = new JObject();
                    Entry.Add("Result", false);
                    Entry.Add("Message", "");
                    Entry.Add("Data", string.Empty);

                    this.QueryInStockEntry(ctx, BillNo, Entry);
                    jVipData.Add("Entry", Entry["Data"]);

                    result["Result"] = true;
                    result["Message"] = "竞价采购入库详情查询成功！";
                    result["Data"] = jVipData;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价采购入库详情查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价采购入库详情失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        #region 竞价采购入库详情查询(采购入库)明细
        internal string QueryInStockEntry(Context ctx, string BillNo, JObject result)
        {
            try
            {
                result["Result"] = false;
                string sql = string.Format(@"/*dialect*/ select 
                                                t2.FNUMBER as Material,
												t3.FNAME as MaterialName,
												t5.FNAME as StockName,
												t6.FNAME as StockStatus,
												t8.FNAME as Owner,
												t1.FREALQTY as Qty,
												t7.FPRICE as CostPrice,
												t1.F_ORA_WHOLESALEPRICE as WholeSalePrice,
												t1.F_ORA_GROUPPRICE as GroupPrice,
												t1.FNOTE as Note
                                                from t_STK_InStock t 
                                                inner join T_STK_INSTOCKENTRY t1 on t1.FID = t.FID
												inner join T_BD_MATERIAL t2 on t2.FMATERIALID = t1.FMATERIALID
												inner join T_BD_MATERIAL_L t3 on t3.FMATERIALID = t2.FMATERIALID and t3.FLOCALEID = 2052
												inner join T_BD_STOCK t4 on t4.FSTOCKID = t1.FSTOCKID
												inner join T_BD_STOCK_L t5 on t5.FSTOCKID = t4.FStockId and t5.FLOCALEID = 2052
												inner join T_BD_STOCKSTATUS_L t6 on t6.FSTOCKSTATUSID = t1.FSTOCKSTATUSID and t6.FLOCALEID = 2052
                                                inner join T_BD_CUSTOMER_L t8 on t8.FCUSTID = t1.FOWNERID and t8.FLOCALEID = 2052
												left join T_STK_INSTOCKENTRY_F t7 on t7.FENTRYID = t1.FENTRYID
												where t.FBILLNO = '{0}'", BillNo);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "采购入库详情成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "采购入库详情完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("采购入库详情失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        //竞价销售出库列表查询
        internal string QueryOutStockList(Context ctx, string Mobile, string OrgNumber, string Status, string BillNo, string BDate, string EDate, int iPageSize, int iPageNum, JObject result)
        {
            result["Result"] = false;
            try
            {
                if (!string.IsNullOrWhiteSpace(BillNo))
                {
                    BillNo = string.Format("AND t.FBILLNO = '{0}'", BillNo);
                }
                if (!string.IsNullOrWhiteSpace(BDate))
                {
                    BDate = string.Format("AND CONVERT(varchar(100), t.FDATE, 120) >= '{0}'", BDate);
                }
                if (!string.IsNullOrWhiteSpace(EDate))
                {
                    EDate = string.Format("AND CONVERT(varchar(100), t.FDATE, 120) <= '{0}'", EDate);
                }
                string sql = "";
                if (Status == "A" || Status == "D")
                {
                    sql = string.Format(@"/*dialect*/select * from (
                                                  SELECT 
                                                ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.FDATE, 120) DESC) AS FIDENTITYID,
                                                T.FBILLNO AS BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                isnull(t4.FNAME,0) as Customer,
												lk.FMOBILE as CusMobile,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核' when t.FDOCUMENTSTATUS = 'D' then '重新审核' when t.FDOCUMENTSTATUS = 'B' then '审核中' when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
												t12.FSYSMBOL as SysMbol,
												t.F_LJX_YF as YFee,
												t.FCARRIAGENO as CarriageNO,
												isnull(t6.FNAME,0) as SalesManID,
												t7.FDATAVALUE as Provice,
												lk.FBIZADDRESS as Adrress,
												lkl.FNAME as Linker
                                                FROM T_SAL_OUTSTOCK T 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FSALEORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052
                                                left join T_BD_CUSTOMER t3 on t3.FCUSTID = t.FCUSTOMERID
                                                left join T_BD_CUSTOMER_L t4 on t4.FCUSTID = t3.FCUSTID and t4.FLOCALEID = 2052
												left join T_BD_COMMONCONTACT lk on lk.FCONTACTID = t.F_QUDE_CUSTOMERLINK
                                                left join T_BD_COMMONCONTACT_L lkl on lkl.FCONTACTID = lk.FCONTACTID and lkl.FLOCALEID = 2052
                                                left join V_BD_SALESMAN t5 on t5.fid = t.FSalesManID 
                                                left join V_BD_SALESMAN_L t6 on t6.fid = t5.fid  and t6.FLOCALEID = 2052
												left join T_BAS_ASSISTANTDATAENTRY_L t7 on t7.FENTRYID = lk.F_QUDE_ASSISTANT1
                                                inner join 
                                                (select t2.FCustomerId as FCustomerId from T_SEC_user t
                                                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
												inner join QUDE_t_StoresFiles t2 on t2.FID = t1.FID
                                                where (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}')
                                                )tf on tf.FCustomerId = t.FCUSTOMERID
												inner JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t.FSALEORGID
                                                inner JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                inner JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                inner JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
                                                where t1.FNUMBER = '{1}'  and (t.FDOCUMENTSTATUS = 'D' OR t.FDOCUMENTSTATUS = 'A')  {4} {5} {6}  ) t
                                                where  t.FIDENTITYID between {2} and {3}", Mobile, OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, BillNo, BDate, EDate);
                }
                else
                {
                    sql = string.Format(@"/*dialect*/select * from (
                                                  SELECT 
                                                ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100), t.FDATE, 120) DESC) AS FIDENTITYID,
                                                T.FBILLNO AS BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                isnull(t4.FNAME,0) as Customer,
												lk.FMOBILE as CusMobile,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核' when t.FDOCUMENTSTATUS = 'D' then '重新审核' when t.FDOCUMENTSTATUS = 'B' then '审核中' when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
												t12.FSYSMBOL as SysMbol,
												t.F_LJX_YF as YFee,
												t.FCARRIAGENO as CarriageNO,
												isnull(t6.FNAME,0) as SalesManID,
												t7.FDATAVALUE as Provice,
												lk.FBIZADDRESS as Adrress,
												lkl.FNAME as Linker
                                                FROM T_SAL_OUTSTOCK T 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FSALEORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052
                                                left join T_BD_CUSTOMER t3 on t3.FCUSTID = t.FCUSTOMERID
                                                left join T_BD_CUSTOMER_L t4 on t4.FCUSTID = t3.FCUSTID and t4.FLOCALEID = 2052
												left join T_BD_COMMONCONTACT lk on lk.FCONTACTID = t.F_QUDE_CUSTOMERLINK
                                                left join T_BD_COMMONCONTACT_L lkl on lkl.FCONTACTID = lk.FCONTACTID and lkl.FLOCALEID = 2052
                                                left join V_BD_SALESMAN t5 on t5.fid = t.FSalesManID 
                                                left join V_BD_SALESMAN_L t6 on t6.fid = t5.fid  and t6.FLOCALEID = 2052
												left join T_BAS_ASSISTANTDATAENTRY_L t7 on t7.FENTRYID = lk.F_QUDE_ASSISTANT1
                                                inner join 
                                                (select t2.FCustomerId as FCustomerId from T_SEC_user t
                                                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
												inner join QUDE_t_StoresFiles t2 on t2.FID = t1.FID
                                                where (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}')
                                                )tf on tf.FCustomerId = t.FCUSTOMERID
												inner JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t.FSALEORGID
                                                inner JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                inner JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                inner JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
                                                where t1.FNUMBER = '{1}'and t.FDOCUMENTSTATUS = '{4}' {5} {6} {7}) t
                                                where  t.FIDENTITYID between {2} and {3}", Mobile, OrgNumber, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, Status, BillNo, BDate, EDate);
                }

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "竞价采购入库列表查询成功！";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价采购入库列表查询成功，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价采购入库列表查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //竞价销售出库详情查询(销售出库)
        internal string QueryOutStock(Context ctx, string BillNo, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                sql = string.Format(@"/*dialect*/ SELECT 
                                                T.FBILLNO AS BillNo,
                                                CONVERT(varchar(100), t.FDATE, 120) as Date,
                                                t1.FNUMBER as OrgNumber,
                                                t2.FNAME as OrgName,
                                                isnull(t4.FNAME,0) as Customer,
												lk.FMOBILE as CusMobile,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核' when t.FDOCUMENTSTATUS = 'D' then '重新审核' when t.FDOCUMENTSTATUS = 'B' then '审核中' when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
												t12.FSYSMBOL as SysMbol,
												t.F_LJX_YF as YFee,
												t.FCARRIAGENO as CarriageNO,
												isnull(t6.FNAME,0) as SalesManID,
												t7.FDATAVALUE as Provice,
												lk.FBIZADDRESS as Adrress,
                                                lkl.FNAME as Linker
                                                FROM T_SAL_OUTSTOCK T 
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FSALEORGID
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052
                                                left join T_BD_CUSTOMER t3 on t3.FCUSTID = t.FCUSTOMERID
                                                left join T_BD_CUSTOMER_L t4 on t4.FCUSTID = t3.FCUSTID and t4.FLOCALEID = 2052
												left join T_BD_COMMONCONTACT lk on lk.FCONTACTID = t.F_QUDE_CUSTOMERLINK
                                                left join T_BD_COMMONCONTACT_L lkl on lkl.FCONTACTID = lk.FCONTACTID and lkl.FLOCALEID = 2052
                                                left join V_BD_SALESMAN t5 on t5.fid = t.FSalesManID 
                                                left join V_BD_SALESMAN_L t6 on t6.fid = t5.fid  and t6.FLOCALEID = 2052
												left join T_BAS_ASSISTANTDATAENTRY_L t7 on t7.FENTRYID = lk.F_QUDE_ASSISTANT1
												inner JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t.FSALEORGID
                                                inner JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                inner JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                inner JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
												where t.FBILLNO = '{0}'", BillNo);

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    JObject jVipData = JObject.FromObject(Datas.First());

                    JObject Entry = new JObject();
                    Entry.Add("Result", false);
                    Entry.Add("Message", "");
                    Entry.Add("Data", string.Empty);

                    this.QueryOutStockEntry(ctx, BillNo, Entry);
                    jVipData.Add("Entry", Entry["Data"]);

                    result["Result"] = true;
                    result["Message"] = "竞价销售出库详情查询成功！";
                    result["Data"] = jVipData;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价销售出库详情查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价销售出库详情失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        #region 竞价销售出库详情查询(销售出库)明细
        internal string QueryOutStockEntry(Context ctx, string BillNo, JObject result)
        {
            try
            {
                result["Result"] = false;
                string sql = string.Format(@"/*dialect*/ select 
                                                t2.FNUMBER as Material,
												t3.FNAME as MaterialName,
												t5.FNAME as StockName,
												t6.FNAME as StockStatus,
												t8.FNAME as Owner,
												t1.FREALQTY as Qty,
												t1.FNOTE as Note
                                                from T_SAL_OUTSTOCK t 
                                                inner join T_SAL_OUTSTOCKENTRY t1 on t1.FID = t.FID
												inner join T_BD_MATERIAL t2 on t2.FMATERIALID = t1.FMATERIALID
												inner join T_BD_MATERIAL_L t3 on t3.FMATERIALID = t2.FMATERIALID and t3.FLOCALEID = 2052
												inner join T_BD_STOCK t4 on t4.FSTOCKID = t1.FSTOCKID
												inner join T_BD_STOCK_L t5 on t5.FSTOCKID = t4.FStockId and t5.FLOCALEID = 2052
												inner join T_BD_STOCKSTATUS_L t6 on t6.FSTOCKSTATUSID = t1.FSTOCKSTATUSID and t6.FLOCALEID = 2052
                                                inner join T_BD_CUSTOMER_L t8 on t8.FCUSTID = t1.FOWNERID and t8.FLOCALEID = 2052
												where t.FBILLNO = '{0}'", BillNo);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "销售出库详情成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "销售出库详情完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("销售出库详情失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 竞价采购价格曲线图
        internal string QueryPurPriceCurve(Context ctx, string OrgNumber, string MaterialNumber, string MaxDate, string MinDate, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                sql = string.Format(@"/*dialect*/ select 
                                                    t2.FNUMBER as MaterialNumber,
                                                    t3.FNUMBER as OrgNumber,
                                                    CONVERT(varchar(100), t.FCREATEDATE, 23) AS ApplicationDate,
                                                    MAX(FPURCHASEPRICE) as PurchasePrice
                                                    from QUDE_BiddingPurchaseOrder t
                                                    inner join QUDE_PurchaseOrderEntry t1 on t1.FID = t.FID
                                                    inner join T_BD_MATERIAL t2 on t2.FMATERIALID = t1.FWINECODE
                                                    inner join T_ORG_ORGANIZATIONS t3 on t3.FORGID = t.FAPPLICATIONORGID
                                                    where t3.FNUMBER = '{0}' and t2.FNUMBER = '{1}' and CONVERT(varchar(100), t.FCREATEDATE, 23) >= '{2}' and  CONVERT(varchar(100), t.FCREATEDATE, 23) <= '{3}'
                                                    GROUP BY t2.FNUMBER,t3.FNUMBER,CONVERT(varchar(100), t.FCREATEDATE, 23)", OrgNumber, MaterialNumber, MinDate, MaxDate);

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "采购曲线图查询成功！";
                    result["Data"] = JArray.FromObject(Datas); ;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "采购曲线图查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("采购曲线图失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 竞价销售价格曲线图
        internal string QuerySalePriceCurve(Context ctx, string OrgNumber, string MaterialNumber, string MaxDate, string MinDate, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                sql = string.Format(@"/*dialect*/select 
                                                    t2.FNUMBER as MaterialNumber,
                                                    t3.FNUMBER as OrgNumber,
                                                    CONVERT(varchar(100), t.FCREATEDATE, 23) AS ApplicationDate,
                                                    Min(FSellingPrice) as SalePrice
                                                    from QUDE_Bidding_SalesOrder t
                                                    inner join QUDE_Sale_OrderEntry t1 on t1.FID = t.FID
                                                    inner join T_BD_MATERIAL t2 on t2.FMATERIALID = t1.FWINECODE
                                                    inner join T_ORG_ORGANIZATIONS t3 on t3.FORGID = t.FAPPLICATIONORGID
                                                    where t3.FNUMBER = '{0}' and t2.FNUMBER = '{1}' and CONVERT(varchar(100), t.FCREATEDATE, 23) >= '{2}' and  CONVERT(varchar(100), t.FCREATEDATE, 23) <= '{3}'
                                                    GROUP BY t2.FNUMBER,t3.FNUMBER,CONVERT(varchar(100), t.FCREATEDATE, 23)", OrgNumber, MaterialNumber, MinDate, MaxDate);

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "销售曲线图查询成功！";
                    result["Data"] = JArray.FromObject(Datas); ;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "销售曲线图查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("销售曲线图失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        //新增公仓入库单（其他入库）
        internal string MISCELLANEOUS(Context ctx, string strParams, JObject result)
        {
            JObject jParams = JObject.Parse(strParams);
            int FID = 0;
            string FStockOrgId = CommonService.GetJParamString(jParams, "FStockOrgId");
            string FDate = CommonService.GetJParamString(jParams, "FDate");
            string FBillNo = CommonService.GetJParamString(jParams, "FBillNo");
            string sql = string.Format(@"/*dialect*/ select FID from T_STK_MISCELLANEOUS where FBILLNO = '{0}'", FBillNo);
            var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
            if (Datas != null && Datas.Count > 0)
            {
                FID = Convert.ToInt32(Datas.First()["FID"]);
            }
            string Supplier = "";
            string Stock = "";
            sql = string.Format(@"/*dialect*/ select t2.FNUMBER as Supplier,t3.FNUMBER as Stock 
                                                        from ora_t_Patformparameter t
                                                        inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.F_ORA_ORGID
                                                        inner join T_BD_SUPPLIER t2 on t2.FSUPPLIERID = t.F_QUDE_Supplier
                                                        inner join T_BD_STOCK t3 on t3.FSTOCKID = t.F_QUDE_Customer
                                                        where t1.FNUMBER = '{0}'", FStockOrgId);
            Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
            if (Datas != null && Datas.Count > 0)
            {
                Supplier = Datas.First()["Supplier"].ToString();
                Stock = Datas.First()["Stock"].ToString();
            }
            else
            {
                result["Message"] = "未查询到区域公仓参数！";
                return result.ToString();
            }

            string FOwnerIdHead = CommonService.GetJParamString(jParams, "FOwnerIdHead");
            string FNOTE = CommonService.GetJParamString(jParams, "FNOTE");
            string F_QUDE_Merchant = CommonService.GetJParamString(jParams, "F_QUDE_Merchant");
            string F_QUDE_Remarks = CommonService.GetJParamString(jParams, "F_QUDE_Remarks");
            string F_QUDE_Date = CommonService.GetJParamString(jParams, "F_QUDE_Date");
            string entity_post_data = "";
            string metails = "";
            string FMATERIALID = "";

            string FQty = "";
            string FPrice = "";
            string F_ora_WholeSalePrice = "";
            string F_ora_GroupPrice = "";
            string FEntryNote = "";
            string FOWNERID = "";
            try
            {
                List<string> entitys = new List<string>();
                //物料
                JArray FBillEntry = JArray.Parse(jParams["FEntity"].ToString());
                foreach (JObject List in FBillEntry)
                {
                    metails = "{\"FMATERIALID\":{\"FNumber\":\"物料编码\"},\"FSTOCKID\":{\"FNumber\":\"仓库编码\"},\"FSTOCKSTATUSID\":{\"FNumber\":\"Normal\"}," +
                        "\"FQty\":数量,\"FPrice\":成本价,\"F_ora_WholeSalePrice\":批发价,\"F_ora_GroupPrice\":团购价,\"FEntryNote\":\"备注\",\"FOWNERTYPEID\":\"BD_Customer\"," +
                        "\"FOWNERID\":{\"FNumber\":\"货主\"}}";
                    FMATERIALID = List["FMATERIALID"].ToString();
                    //Stock = List["FSTOCKID"].ToString();
                    FQty = List["FQty"].ToString();
                    FPrice = List["FPrice"].ToString();
                    F_ora_WholeSalePrice = List["F_ora_WholeSalePrice"].ToString();
                    F_ora_GroupPrice = List["F_ora_GroupPrice"].ToString();
                    FEntryNote = List["FEntryNote"].ToString();
                    FOWNERID = List["FOWNERID"].ToString();
                    metails = metails.Replace("物料编码", FMATERIALID);
                    metails = metails.Replace("仓库编码", Stock);
                    metails = metails.Replace("数量", FQty);
                    metails = metails.Replace("成本价", FPrice);
                    metails = metails.Replace("批发价", F_ora_WholeSalePrice);
                    metails = metails.Replace("团购价", F_ora_GroupPrice);
                    metails = metails.Replace("备注", FEntryNote);
                    metails = metails.Replace("货主", FOWNERID);
                    entitys.Add(metails);
                }
                if (entitys.Count > 0)
                {
                    for (int j = 0; j < entitys.Count; j++)
                    {
                        entity_post_data = entity_post_data + entitys[j] + ",";
                    }
                }
                entity_post_data = entity_post_data.Remove(entity_post_data.Length - 1, 1);
                string metail = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"false\",\"IsEntryBatchFill\":\"true\"," +
                    "\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\"," +
                    "\"Model\":{\"FID\":主键,\"FBillTypeID\":{\"FNUMBER\":\"QTRKD01_SYS\"},\"FStockOrgId\":{\"FNumber\":\"库存组织\"},\"FStockDirect\":\"GENERAL\",\"FDate\":\"单据日期\"," +
                    "\"FSUPPLIERID\":{\"FNumber\":\"供应商\"},\"FOwnerTypeIdHead\":\"BD_Customer\",\"FOwnerIdHead\":{\"FNumber\":\"货主\"},\"FNOTE\":\"备注\",\"F_QUDE_Merchant\":{\"FNUMBER\":\"商家信息\"}," +
                    "\"F_QUDE_Remarks\":\"物流信息\",\"F_QUDE_Date\":\"到货日期\",\"FEntity\":[明细]}}";
                metail = metail.Replace("主键", FID.ToString());
                metail = metail.Replace("库存组织", FStockOrgId);
                metail = metail.Replace("单据日期", FDate);
                metail = metail.Replace("供应商", Supplier);
                metail = metail.Replace("货主", FOwnerIdHead);
                metail = metail.Replace("备注", FNOTE);
                metail = metail.Replace("商家信息", F_QUDE_Merchant);
                metail = metail.Replace("物流信息", F_QUDE_Remarks);
                metail = metail.Replace("到货日期", F_QUDE_Date);
                metail = metail.Replace("明细", entity_post_data);
                Logger.Info("STK_MISCELLANEOUS", metail.ToString());
                JObject resule = CommonService.SaveMethod(ctx, "STK_MISCELLANEOUS", metail);
                if (CommonService.GetJParamString(resule, "code") == "200")
                {
                    string Number = CommonService.GetJParamString(resule, "Number");
                    result["Result"] = true;
                    result["Message"] = "创建入库单成功！";
                    JObject Data = new JObject();
                    Data.Add("BillNo", Number); //编码
                    result["Data"] = Data;
                }
                else
                {
                    result["Message"] = CommonService.GetJParamString(resule, "msg");
                }
            }
            catch (Exception e)
            {
                result["Result"] = false;
                result["Message"] = "数据格式不正确！" + e.Message;
            }
            return result.ToString();
        }


        //新增公仓出库单（其他出库单）
        internal string STK_MisDelivery(Context ctx, string strParams, JObject result)
        {
            JObject jParams = JObject.Parse(strParams);
            int FID = 0;
            string FBillNo = CommonService.GetJParamString(jParams, "FBillNo");
            string sql = string.Format(@"/*dialect*/ select FID from T_STK_MISDELIVERY where FBILLNO = '{0}'", FBillNo);
            var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
            if (Datas != null && Datas.Count > 0)
            {
                FID = Convert.ToInt32(Datas.First()["FID"]);
            }
            string FStockOrgId = CommonService.GetJParamString(jParams, "FStockOrgId");
            string FDate = CommonService.GetJParamString(jParams, "FDate");
            string FOwnerIdHead = CommonService.GetJParamString(jParams, "FOwnerIdHead");
            string FCustId = CommonService.GetJParamString(jParams, "FCustId");
            string FNote = CommonService.GetJParamString(jParams, "FNOTE");
            string F_QUDE_Merchant = CommonService.GetJParamString(jParams, "F_QUDE_Merchant");
            string F_QUDE_Remarks = CommonService.GetJParamString(jParams, "F_QUDE_Remarks");
            string F_QUDE_Date = CommonService.GetJParamString(jParams, "F_QUDE_Date");
            string F_QUDE_FEE = CommonService.GetJParamString(jParams, "F_QUDE_FEE");
            string entity_post_data = "";
            string metails = "";
            string FMATERIALID = "";
            string FQty = "";
            string SalePrice = "";
            string FEntryNote = "";
            string FOWNERID = "";
            string Stock = "";
            sql = string.Format(@"/*dialect*/ select t3.FNUMBER as Stock 
                                                        from ora_t_Patformparameter t
                                                        inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.F_ORA_ORGID
                                                        inner join T_BD_STOCK t3 on t3.FSTOCKID = t.F_QUDE_Customer
                                                        where t1.FNUMBER = '{0}'", FStockOrgId);
            Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
            if (Datas != null && Datas.Count > 0)
            {
                Stock = Datas.First()["Stock"].ToString();
            }
            else
            {
                result["Message"] = "未查询到区域公仓参数！";
                return result.ToString();
            }
            try
            {
                List<string> entitys = new List<string>();
                //物料
                JArray FBillEntry = JArray.Parse(jParams["FEntity"].ToString());
                foreach (JObject List in FBillEntry)
                {
                    metails = "{\"FMaterialId\":{\"FNumber\":\"物料编码\"},\"FQty\":数量,\"FPRICE\":销售价格,\"FStockId\":{\"FNumber\":\"仓库编码\"},\"FOwnerTypeId\":\"BD_Customer\"," +
                        "\"FOwnerId\":{\"FNumber\":\"货主\"},\"FEntryNote\":\"备注\",\"FStockStatusId\":{\"FNumber\":\"Normal\"}}";
                    FMATERIALID = List["FMaterialId"].ToString();
                    //FSTOCKID = List["FStockId"].ToString();
                    FQty = List["FQty"].ToString();
                    SalePrice = List["FSalePrice"].ToString();
                    FEntryNote = List["FEntryNote"].ToString();
                    FOWNERID = List["FOwnerId"].ToString();
                    metails = metails.Replace("物料编码", FMATERIALID);
                    metails = metails.Replace("仓库编码", Stock);
                    metails = metails.Replace("数量", FQty);
                    metails = metails.Replace("销售价格", SalePrice);
                    metails = metails.Replace("备注", FEntryNote);
                    metails = metails.Replace("货主", FOWNERID);
                    entitys.Add(metails);
                }
                if (entitys.Count > 0)
                {
                    for (int j = 0; j < entitys.Count; j++)
                    {
                        entity_post_data = entity_post_data + entitys[j] + ",";
                    }
                }
                entity_post_data = entity_post_data.Remove(entity_post_data.Length - 1, 1);
                string metail = "{\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"IsDeleteEntry\":\"true\",\"SubSystemId\":\"\",\"IsVerifyBaseDataField\":\"false\",\"IsEntryBatchFill\":\"true\"," +
                    "\"ValidateFlag\":\"true\",\"NumberSearch\":\"true\",\"IsAutoAdjustField\":\"false\",\"InterationFlags\":\"\",\"IgnoreInterationFlag\":\"\",\"IsControlPrecision\":\"false\"," +
                    "\"Model\":{\"FID\":主键,\"FBillTypeID\":{\"FNUMBER\":\"QTCKD01_SYS\"},\"FStockOrgId\":{\"FNumber\":\"库存组织\"},\"FPickOrgId\":{\"FNumber\":\"库存组织\"},\"FOwnerTypeIdHead\":\"BD_Customer\"," +
                    "\"F_QUDE_Merchant\":{\"FNumber\":\"商家信息\"},\"FOwnerIdHead\":{\"FNumber\":\"货主\"},\"FStockDirect\":\"GENERAL\",\"FDate\":\"单据日期\"," +
                    "\"FCustId\":{\"FNumber\":\"客户\"},\"FNote\":\"备注\",\"F_QUDE_Date\":\"到货日期\",\"F_QUDE_Remarks\":\"物流信息\",\"F_QUDE_FEE\":\"运费\",\"FEntity\":[明细]}}";
                metail = metail.Replace("主键", FID.ToString());
                metail = metail.Replace("库存组织", FStockOrgId);
                metail = metail.Replace("单据日期", FDate);
                metail = metail.Replace("客户", FCustId);
                metail = metail.Replace("货主", FOwnerIdHead);
                metail = metail.Replace("备注", FNote);
                metail = metail.Replace("商家信息", F_QUDE_Merchant);
                metail = metail.Replace("物流信息", F_QUDE_Remarks);
                metail = metail.Replace("到货日期", F_QUDE_Date);
                metail = metail.Replace("运费", F_QUDE_FEE);
                metail = metail.Replace("明细", entity_post_data);
                Logger.Info("STK_MisDelivery", metail.ToString());
                JObject resule = CommonService.SaveMethod(ctx, "STK_MisDelivery", metail);
                if (CommonService.GetJParamString(resule, "code") == "200")
                {
                    string Number = CommonService.GetJParamString(resule, "Number");
                    result["Result"] = true;
                    result["Message"] = "创建出库单成功！";
                    JObject Data = new JObject();
                    Data.Add("BillNo", Number); //编码
                    result["Data"] = Data;
                }
                else
                {
                    result["Message"] = CommonService.GetJParamString(resule, "msg");
                }
            }
            catch (Exception e)
            {
                result["Result"] = false;
                result["Message"] = "数据格式不正确！" + e.Message;
            }
            return result.ToString();
        }


        //通用操作按钮
        internal string GeneralButton(Context ctx, string strParams, JObject result)
        {
            JObject jParams = JObject.Parse(strParams);
            result["Result"] = false;
            string BillTypeID = CommonService.GetJParamString(jParams, "BillTypeID");
            string OperationType = CommonService.GetJParamString(jParams, "OperationType");
            string BillNo = CommonService.GetJParamString(jParams, "BillNo");
            JObject Results;
            try
            {
                string all = "{\"Numbers\":[\"编码\"]}";
                string json = all.Replace("编码", BillNo);
                if (OperationType == "Submit")
                {
                    Results = CommonService.SubmitMethod(ctx, BillTypeID, json);
                    if (CommonService.GetJParamString(Results, "code") == "200")
                    {
                        string Number = CommonService.GetJParamString(Results, "Number");
                        result["Result"] = true;
                        result["Message"] = "提交单据成功！";
                        JObject Data = new JObject();
                        Data.Add("BillNo", Number); //编码
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(Results, "msg");
                    }
                }
                else if (OperationType == "Audit")
                {
                    Results = CommonService.AuditMethod(ctx, BillTypeID, json);
                    if (CommonService.GetJParamString(Results, "code") == "200")
                    {
                        string Number = CommonService.GetJParamString(Results, "Number");
                        result["Result"] = true;
                        result["Message"] = "审核单据成功！";
                        JObject Data = new JObject();
                        Data.Add("BillNo", Number); //编码
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(Results, "msg");
                    }
                }
                else if (OperationType == "UnAudit")
                {
                    Results = CommonService.UnAuditMethod(ctx, BillTypeID, json);
                    if (CommonService.GetJParamString(Results, "code") == "200")
                    {
                        string Number = CommonService.GetJParamString(Results, "Number");
                        result["Result"] = true;
                        result["Message"] = "反审核单据成功！";
                        JObject Data = new JObject();
                        Data.Add("BillNo", Number); //编码
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(Results, "msg");
                    }
                }
                if (OperationType == "Delete")
                {
                    Results = CommonService.DeleteMethod(ctx, BillTypeID, json);
                    if (CommonService.GetJParamString(Results, "code") == "200")
                    {
                        string Number = CommonService.GetJParamString(Results, "Number");
                        result["Result"] = true;
                        result["Message"] = "删除单据成功！";
                        JObject Data = new JObject();
                        Data.Add("BillNo", Number); //编码
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(Results, "msg");
                    }
                }
                if (OperationType == "CancelAssign")
                {
                    Results = CommonService.CancelAssign(ctx, BillTypeID, json);
                    if (CommonService.GetJParamString(Results, "code") == "200")
                    {
                        string Number = CommonService.GetJParamString(Results, "Number");
                        result["Result"] = true;
                        result["Message"] = "撤销单据成功！";
                        JObject Data = new JObject();
                        Data.Add("BillNo", Number); //编码
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(Results, "msg");
                    }
                }

            }
            catch (Exception e)
            {
                result["Result"] = false;
                result["Message"] = "数据格式不正确！" + e.Message;
            }
            return result.ToString();
        }

        #region 即时库存列表
        internal string Inventory(Context ctx, string Mobile, string OrgNumber, string MaterialNumber, string MaterialName, string Type, string DCost, string LCost, string DTradePrice, string LTradePrice, string DGroupPrice, string LGroupPrice, string DBaseQty, string LBaseQty, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                string PurMerchant = "";
                string SaleMerchant = "";
                decimal BidPrice = 0;
                decimal OfferPrice = 0;
                string sql = "";
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("/*dialect*/SELECT count(1) over() as TotalCount, StockOrgNumber,StockOrgName,MaterialNumber,MaterialName,Customer,Type,Cost,TradePrice,GroupPrice,SysMbol,BaseQty,StoresFiles, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY BaseQty DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendFormat(@"/*dialect*/(SELECT 
                                    O.FNUMBER AS StockOrgNumber,
                                    OL.FNAME StockOrgName,
                                    M.FNUMBER AS MaterialNumber, 
                                    ML.FNAME AS MaterialName,
                                    t8.FID AS StoresFiles,
                                    CSL.FNAME AS Customer,
                                    ISNULL(LXL.FDATAVALUE,0) AS Type,
                                    ISNULL(t6.F_QUDE_COST,0) as Cost,--成本
                                    ISNULL(t6.F_QUDE_TRADEPRICE,0) as TradePrice,--批发
                                    ISNULL(t6.F_QUDE_GROUPPRICE,0) as GroupPrice,--团购
                                    t12.FSYSMBOL AS SysMbol,
                                    sum(TI.FBASEQTY - isnull(tsub.fbaselockqty,0)) AS BaseQty--可用量
                                    FROM T_STK_INVENTORY TI
                                    LEFT OUTER JOIN T_ORG_ORGANIZATIONS O ON (TI.FSTOCKORGID = O.FORGID)
                                    LEFT OUTER JOIN T_ORG_ORGANIZATIONS_L OL ON ( TI.FSTOCKORGID = OL.FORGID AND OL.FLOCALEID = 2052)
                                    INNER JOIN T_BD_MATERIAL M ON ( M.FMASTERID = TI.FMATERIALID AND (M.FUSEORGID = TI.FSTOCKORGID OR EXISTS (SELECT 1 FROM T_META_BASEDATATYPE BT WHERE(BT.FBASEDATATYPEID = 'BD_MATERIAL' AND BT.FSTRATEGYTYPE = 1))))
                                    LEFT OUTER JOIN T_BD_MATERIAL_L ML ON (M.FMATERIALID = ML.FMATERIALID AND ML.FLOCALEID = 2052)
                                    left join ora_t_Cust100034 LX on LX.FID = M.FWINEBASE1
                                    left join T_BAS_ASSISTANTDATAENTRY_L LXL on LXL.FENTRYID = LX.FSTYLE and LXL.FLOCALEID  = 2052
                                    LEFT OUTER JOIN (SELECT TLKE.FSUPPLYINTERID finventryid, SUM (TLKE.FBASEQTY) fbaselockqty, SUM (TLKE.FSECQTY) fseclockqty FROM T_PLN_RESERVELINKENTRY TLKE INNER JOIN T_PLN_RESERVELINK TLKH ON TLKE.FID = TLKH.FID WHERE(TLKE.FSUPPLYFORMID = 'STK_Inventory' AND TLKE.FLINKTYPE = '4')GROUP BY TLKE.FSUPPLYINTERID) tsub ON TI.FID = TSUB.FINVENTRYID
                                    INNER JOIN T_BD_CUSTOMER_L CSL ON CSL.FCUSTID = TI.FOWNERID AND CSL.FLOCALEID = 2052
                                    LEFT JOIN QUDE_t_StoresFiles t8 on t8.FCustomerId = TI.FOWNERID
                                    LEFT JOIN F_Price_Entity t6 ON M.FMATERIALID = t6.FMATERIALID AND t8.FID = t6.F_QUDE_STOREIN
                                            INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= O.FORGID
                                            INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                            INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                            INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID

                inner join 
                (select t1.FID as FID from T_SEC_user t 
                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
                where (REPLACE(t.FPHONE, '-', '') ='{1}' or  REPLACE(t.FPHONE, '+', '') ='{1}')
                )tf on tf.FID = t8.FID
                                    WHERE TI.FBASEQTY - isnull(tsub.fbaselockqty,0) > 0 and O.FNUMBER = '{0}'
                                                ", OrgNumber, Mobile);
                if (!string.IsNullOrWhiteSpace(MaterialNumber))
                {
                    MaterialNumber = "%" + MaterialNumber + "%";
                    sbSql.AppendLine(" AND M.FNUMBER LIKE  @MaterialNumber");
                    lstParam.Add(new SqlParam("@MaterialNumber", KDDbType.String, MaterialNumber));
                }
                if (!string.IsNullOrWhiteSpace(MaterialName))
                {
                    MaterialName = "%" + MaterialName.Replace("-", " ") + "%";
                    sbSql.AppendLine(" AND REPLACE(ML.FNAME, '-', ' ') LIKE  @MaterialName");
                    lstParam.Add(new SqlParam("@MaterialName", KDDbType.String, MaterialName));
                }
                if (!string.IsNullOrWhiteSpace(Type))
                {
                    sbSql.AppendLine(" AND ISNULL(LXL.FDATAVALUE,0) =  @Type");
                    lstParam.Add(new SqlParam("@Type", KDDbType.String, Type));
                }

                if (!string.IsNullOrWhiteSpace(DCost))
                {
                    sbSql.AppendLine(" AND ISNULL(t6.F_QUDE_COST,0) >=  @DCost");
                    lstParam.Add(new SqlParam("@DCost", KDDbType.String, DCost));
                }
                if (!string.IsNullOrWhiteSpace(LCost))
                {
                    sbSql.AppendLine(" AND ISNULL(t6.F_QUDE_COST,0) <=  @LCost");
                    lstParam.Add(new SqlParam("@LCost", KDDbType.String, LCost));
                }

                if (!string.IsNullOrWhiteSpace(DTradePrice))
                {
                    sbSql.AppendLine(" AND ISNULL(t6.F_QUDE_TRADEPRICE,0) >=  @DTradePrice");
                    lstParam.Add(new SqlParam("@DTradePrice", KDDbType.String, DTradePrice));
                }
                if (!string.IsNullOrWhiteSpace(LTradePrice))
                {
                    sbSql.AppendLine(" AND ISNULL(t6.F_QUDE_TRADEPRICE,0) <=  @LTradePrice");
                    lstParam.Add(new SqlParam("@LTradePrice", KDDbType.String, LTradePrice));
                }
                if (!string.IsNullOrWhiteSpace(DGroupPrice))
                {
                    sbSql.AppendLine(" AND ISNULL(t6.F_QUDE_GROUPPRICE,0) >=  @DGroupPrice");
                    lstParam.Add(new SqlParam("@DGroupPrice", KDDbType.String, DGroupPrice));
                }
                if (!string.IsNullOrWhiteSpace(LGroupPrice))
                {
                    sbSql.AppendLine(" AND ISNULL(t6.F_QUDE_GROUPPRICE,0) <=  @LGroupPrice");
                    lstParam.Add(new SqlParam("@LGroupPrice", KDDbType.String, LGroupPrice));
                }

                if (!string.IsNullOrWhiteSpace(DBaseQty))
                {
                    sbSql.AppendLine(" AND TI.FBASEQTY - isnull(tsub.fbaselockqty,0) >=  @DBaseQty");
                    lstParam.Add(new SqlParam("@DBaseQty", KDDbType.String, DBaseQty));
                }
                if (!string.IsNullOrWhiteSpace(LBaseQty))
                {
                    sbSql.AppendLine(" AND TI.FBASEQTY - isnull(tsub.fbaselockqty,0) <=  @LBaseQty");
                    lstParam.Add(new SqlParam("@LBaseQty", KDDbType.String, LBaseQty));
                }

                sbSql.AppendLine(@" group by O.FNUMBER,
                                            OL.FNAME,t8.FID,
                                            M.FNUMBER,
                                            ML.FNAME,
                                            CSL.FNAME, F_QUDE_COST, F_QUDE_TRADEPRICE,t12.FSYSMBOL,
                                            F_QUDE_GROUPPRICE,LXL.FDATAVALUE)ts ");
                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));
                sbSql.AppendFormat(@"/*dialect*/select FIDENTITYID,TotalCount,StockOrgNumber,StockOrgName,MaterialNumber,MaterialName,Customer,Type,Cost,TradePrice,GroupPrice,SysMbol,BaseQty,case when tis.FViewPermissionStatusName = 1 then 0 when tis.FViewPermissionStatusName is null then 1 else 1 end IsView  FROM {0} t
                
                left join (select distinct u.FName FUserName,r2.FNAME role,u.FPHONE mobile,org1.FNumber org,
                    f2.FView  FViewPermissionStatusName
                    from T_SEC_FIELDPERMISSION f1
                    inner join T_SEC_FIELDPERMISSIONEntry f2 on f1.FITEMID=f2.FITEMID
                    inner join t_sec_role r1 on f1.FRoleID = r1.FRoleID --角色
                    left join t_sec_role_l r2 on r2.FRoleID=r1.FRoleID and r2.FLOCALEID=2052 --角色多语言 
                    inner join t_sec_userrolemap uor on uor.FROLEID= r1.FROLEID --用户角色关系
                    inner join T_SEC_USERORG uo on uo.FENTITYID=uor.FENTITYID --用户组织关系
                    inner join t_sec_User u on uo.FUserID=u.FUserID --用户
                    inner join t_org_organizations org1 on org1.FOrgID=uo.FOrgID --组织
                    left join t_org_organizations_l org2 on org1.FOrgID = org2.FOrgID and org2.FLOCALEID=2052 --组织多语言
                    inner join t_meta_objectType o1 on f1.FObjectTypeID=o1.FID
                    left join v_meta_objectType_l o2 on f1.FObjectTypeId= o2.FID and o2.FLOCALEID=2052 --业务对象多语言
                    inner join t_meta_subsystem s1 on o1.FSUBSYSID = s1.FID --子系统
                    left join t_meta_subsystem_l s2 on s1.FID = s2.FID and s2.FLOCALEID=2052 --子系统多语言
                    inner join T_META_TOPCLASS t1 on t1.FTOPCLASSID= s1.FTOPCLASSID --子系统分组（业务领域）
                    left join T_META_TOPCLASS_L t2 on t2.FTOPCLASSID= t1.FTOPCLASSID and t2.FLOCALEID=2052 --子系统多语言--  
                    where f1.FObjectTypeId = 'STK_Inventory' and FFIELDKEY = 'F_QUDE_Price' and (REPLACE(u.FPHONE, '-', '') ='{3}' or  REPLACE(u.FPHONE, '+', '') ='{3}') and org1.FNumber = '{4}'
                    )tis on  tis.org = t.StockOrgNumber
                where FIDENTITYID between {1}
                and {2}", strTempTable, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, Mobile, OrgNumber);

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    JObject Data = new JObject();
                    Data.Add("TotalCount", Convert.ToInt64(TotalDatas.First()["TotalCount"]));
                    Data.Add("Datas", JArray.FromObject(TotalDatas));
                    result["Result"] = true;
                    result["Message"] = "即时库存查询成功";
                    result["Data"] = Data;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "即时库存查询成功，返回查询结果为空！";
                }
                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("即时库存查询成功查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        //更新商品价格
        internal string UpdateMaterialPrcie(Context ctx, string Mobile, string OrgNumber, string MaterialNumber, string Cost, string TradePrice, string GroupPrice, JObject result)
        {
            result["Result"] = false;
            try
            {
                //string _strFormID = "STK_Inventory";
                //BusinessObject _bo = new BusinessObject
                //{
                //    Id = _strFormID
                //};
                //if (!PermissionServiceHelper.FuncPermissionAuth(ctx, _bo, "625a5c8191da8f").Passed)
                //{
                //    result["Message"] = "没有更新价格权限！";
                //    return result.ToString();
                //}
                string fitemstatus = "";
                string sql = string.Format(@"/*dialect*/SELECT FU.FOBJECTTYPEID fobjecttypeid,U.FNAME fuername,FUE.FPERMISSIONSTATUS fitemstatus
                                                FROM T_SEC_ROLE R
                                                LEFT JOIN T_SEC_ROLE_L RL ON RL.FROLEID = R.FROLEID AND RL.FLOCALEID = 2052
                                                INNER JOIN T_SEC_FUNCPERMISSION FU ON FU.FROLEID = R.FROLEID 
                                                INNER JOIN T_SEC_FUNCPERMISSIONENTRY FUE ON FUE.FITEMID = FU.FITEMID
                                                LEFT JOIN T_SEC_PERMISSIONITEM_L PIL ON PIL.FITEMID = FUE.FPERMISSIONITEMID AND PIL.FLOCALEID = 2052
                                                LEFT JOIN T_SEC_DATARULE_L DRL ON DRL.FITEMID = FUE.FDATARULE AND DRL.FLOCALEID = 2052
                                                LEFT JOIN T_SEC_FIELDPERMISSION FE ON FE.FROLEID = R.FROLEID AND FU.FOBJECTTYPEID  = FE.FOBJECTTYPEID
                                                LEFT JOIN (SELECT DISTINCT PO.FROLEID,POE.FOBJECTTYPEID
                                                FROM T_SEC_POSTPERMISSION PO 
                                                LEFT JOIN T_SEC_POSTPERMISSIONENTRY POE ON POE.FPERMISSIONID = PO.FPERMISSIONID 
                                                ) PO  ON  PO.FROLEID = R.FROLEID AND PO.FOBJECTTYPEID = FU.FOBJECTTYPEID
                                                INNER JOIN T_META_OBJECTTYPE OB ON OB.FID = FU.FOBJECTTYPEID 
                                                LEFT JOIN V_META_OBJECTTYPE_L OBL ON OBL.FID = OB.FID AND OBL.FLOCALEID = 2052
                                                INNER JOIN T_META_SUBSYSTEM SU ON SU.FID = OB.FSUBSYSID 
                                                LEFT JOIN T_META_SUBSYSTEM_L SUL ON SUL.FID = OB.FSUBSYSID AND SUL.FLOCALEID = 2052
                                                INNER JOIN T_SEC_USERROLEMAP ROG ON ROG.FROLEID = R.FROLEID
                                                INNER JOIN T_SEC_USERORG UOG ON UOG.FENTITYID = ROG.FENTITYID
                                                INNER JOIN T_SEC_USER U ON U.FUSERID = UOG.FUSERID
                                                LEFT JOIN T_ORG_ORGANIZATIONS OG ON OG.FORGID = UOG.FORGID
                                                LEFT JOIN T_ORG_ORGANIZATIONS_L OGL ON OGL.FORGID = UOG.FORGID AND OGL.FLOCALEID = 2052
                                                WHERE 1=1 and (REPLACE(U.FPHONE, '-', '') ='{0}' or  REPLACE(U.FPHONE, '+', '') ='{0}') AND OG.FNUMBER = '{1}' AND FU.FOBJECTTYPEID = 'STK_Inventory' and PIL.FNAME = '即时库存价格修改'", Mobile, OrgNumber);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    fitemstatus = Convert.ToString(Datas.First()["fitemstatus"]);
                    if (fitemstatus == "0")
                    {
                        sql = string.Format(@"/*dialect*/UPDATE t1 set  t1.F_QUDE_COST = '{2}',t1.F_QUDE_TRADEPRICE = '{3}',t1.F_QUDE_GROUPPRICE = '{4}' FROM F_Price_Entity t1 
                                                INNER JOIN QUDE_t_StoresFiles t2 ON t1.F_QUDE_STOREIN = t2.FID
                                                inner join 
                                                                (select t1.FID as FID from T_SEC_user t 
                                                                inner join QUDE_StoreEntity t1 on t1.F_QUDE_STOREFILE = t.FUSERID
                                                                where (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}')
                                                                )tf on tf.FID = t2.FID
                                                INNER JOIN T_BD_MATERIAL t3 on t3.FMATERIALID = t1.FMATERIALID
                                                INNER JOIN T_ORG_ORGANIZATIONS T4 ON T4.FORGID = T3.FUSEORGID
                                                 WHERE t3.FNUMBER  = '{1}' and  t4.FNUMBER = '{5}'", Mobile, MaterialNumber, Cost, TradePrice, GroupPrice, OrgNumber);
                        DBUtils.Execute(ctx, sql);
                        result["Result"] = true;
                        result["Message"] = "更新价格成功！";
                    }
                    else
                    {
                        result["Message"] = "请联系客服，重新授权!";
                    }
                }
                else
                {
                    result["Message"] = "请联系客服，重新授权!";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("更新价格失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //查询区域信息
        internal string QueryArea(Context ctx, string Number, JObject result)
        {
            result["Result"] = false;
            try
            {
                if (!string.IsNullOrWhiteSpace(Number))
                {
                    Number = string.Format("AND T.FNUMBER = '{0}'", Number);
                }
                string sql = string.Format(@"select t.FNUMBER as Number , t1.FNAME  as Name,t.FIsRights as IsRights,t14.FNAME  AS Currency,
                                            t12.FSYSMBOL AS SysMbol
                                            from  T_ORG_ORGANIZATIONS t 
                                            inner join T_ORG_ORGANIZATIONS_L t1 on t1.FORGID = t.FORGID and t1.FLOCALEID = 2052
                                            INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t1.FORGID
                                            INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                            INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                            INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                            INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = 2052
                                                            where 1=1 {0}", Number);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "区域查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "区域查询，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("区域查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }


        //包装列表查询
        internal string QueryUnitlist(Context ctx, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"select FNUMBER as FNUMBER ,t1.FNAME as FNAME,t2.FXCONVERTNUMERATOR  as XCONVERTNUMERATOR
                                from T_BD_UNIT t
                                inner join T_BD_UNIT_L t1 on t1.FUNITID = t.FUNITID and t1.FLOCALEID = 2052
                                left join T_BD_UNITCONVERTRATE t2 ON t2.FUNITID = t1.FUNITID
                                 where F_QDQP_CHECKBOX = 1 and t.FDOCUMENTSTATUS = 'C' and t.FNUMBER <> 'LS'");
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "包装列表查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "包装列表查询，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("包装列表查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //规格列表查询
        internal string QuerySizelist(Context ctx, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"select T.FNUMBER as NUMBER,T1.FDATAVALUE AS NAME from T_BAS_ASSISTANTDATAENTRY t 
                                            inner join T_BAS_ASSISTANTDATAENTRY_L t1 on t1.FENTRYID = t.FENTRYID
                                            where t.FID = '61b8b0a488073a' and t.FDOCUMENTSTATUS = 'C'");
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "规格列表查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "规格列表查询，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("规格列表查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //库存修改价格权限查询
        internal string QueryUpdatePrice(Context ctx, string Mobile, string OrgNumber, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"SELECT FU.FOBJECTTYPEID FOBJECTTYPEID,U.FNAME FUERNAME,FUE.FPERMISSIONSTATUS FITEMSTATUS
                                                FROM T_SEC_ROLE R
                                                LEFT JOIN T_SEC_ROLE_L RL ON RL.FROLEID = R.FROLEID AND RL.FLOCALEID = 2052
                                                INNER JOIN T_SEC_FUNCPERMISSION FU ON FU.FROLEID = R.FROLEID 
                                                INNER JOIN T_SEC_FUNCPERMISSIONENTRY FUE ON FUE.FITEMID = FU.FITEMID
                                                LEFT JOIN T_SEC_PERMISSIONITEM_L PIL ON PIL.FITEMID = FUE.FPERMISSIONITEMID AND PIL.FLOCALEID = 2052
                                                LEFT JOIN T_SEC_DATARULE_L DRL ON DRL.FITEMID = FUE.FDATARULE AND DRL.FLOCALEID = 2052
                                                LEFT JOIN T_SEC_FIELDPERMISSION FE ON FE.FROLEID = R.FROLEID AND FU.FOBJECTTYPEID  = FE.FOBJECTTYPEID
                                                LEFT JOIN (SELECT DISTINCT PO.FROLEID,POE.FOBJECTTYPEID
                                                FROM T_SEC_POSTPERMISSION PO 
                                                LEFT JOIN T_SEC_POSTPERMISSIONENTRY POE ON POE.FPERMISSIONID = PO.FPERMISSIONID 
                                                ) PO  ON  PO.FROLEID = R.FROLEID AND PO.FOBJECTTYPEID = FU.FOBJECTTYPEID
                                                INNER JOIN T_META_OBJECTTYPE OB ON OB.FID = FU.FOBJECTTYPEID 
                                                LEFT JOIN V_META_OBJECTTYPE_L OBL ON OBL.FID = OB.FID AND OBL.FLOCALEID = 2052
                                                INNER JOIN T_META_SUBSYSTEM SU ON SU.FID = OB.FSUBSYSID 
                                                LEFT JOIN T_META_SUBSYSTEM_L SUL ON SUL.FID = OB.FSUBSYSID AND SUL.FLOCALEID = 2052
                                                INNER JOIN T_SEC_USERROLEMAP ROG ON ROG.FROLEID = R.FROLEID
                                                INNER JOIN T_SEC_USERORG UOG ON UOG.FENTITYID = ROG.FENTITYID
                                                INNER JOIN T_SEC_USER U ON U.FUSERID = UOG.FUSERID
                                                LEFT JOIN T_ORG_ORGANIZATIONS OG ON OG.FORGID = UOG.FORGID
                                                LEFT JOIN T_ORG_ORGANIZATIONS_L OGL ON OGL.FORGID = UOG.FORGID AND OGL.FLOCALEID = 2052
                                                WHERE 1=1 and (REPLACE(U.FPHONE, '-', '') ='{0}' or  REPLACE(U.FPHONE, '+', '') ='{0}') AND OG.FNUMBER = '{1}' AND FU.FOBJECTTYPEID = 'STK_Inventory' and PIL.FNAME = '即时库存价格修改'", Mobile, OrgNumber);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "用户更新价格权限查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Message"] = "请联系客服，重新授权!";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("用户查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //查询用户信息
        internal string QueryUser(Context ctx, string Mobile, string OrgNumber, JObject result)
        {
            result["Result"] = false;
            try
            {

                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    OrgNumber = string.Format("and t2.FNUMBER = '{0}'", OrgNumber);
                }
                else
                {
                    OrgNumber = "";
                }
                string sql = string.Format(@"select t2.FNUMBER as ORGNUMBER,t3.FNAME as ORGNAME, t2.FIsRights as IsRights from T_SEC_user t 
                                            inner join t_sec_userorg t1 on t1.FUSERID = t.FUSERID
                                            inner join T_ORG_ORGANIZATIONS t2 on t2.FORGID = t1.FORGID
                                            inner join T_ORG_ORGANIZATIONS_L t3 on t3.FORGID = t2.FORGID  and t3.FLOCALEID = 2052 
                                            where t2.FIsRights = 1 and (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}') {1}", Mobile, OrgNumber);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "用户查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "用户未注册！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("用户查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }


        //查询用户组织信息
        internal string QueryUserOrg(Context ctx, string Mobile, string OrgNumber, JObject result)
        {
            result["Result"] = false;
            try
            {

                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    OrgNumber = string.Format("and t2.FNUMBER = '{0}'", OrgNumber);
                }
                else
                {
                    OrgNumber = "";
                }
                string sql = string.Format(@"select t2.FNUMBER as ORGNUMBER,t3.FNAME as ORGNAME  from T_SEC_user t 
                                            inner join t_sec_userorg t1 on t1.FUSERID = t.FUSERID
                                            inner join T_ORG_ORGANIZATIONS t2 on t2.FORGID = t1.FORGID
                                            inner join T_ORG_ORGANIZATIONS_L t3 on t3.FORGID = t2.FORGID  and t3.FLOCALEID = 2052 
                                            where  (REPLACE(t.FPHONE, '-', '') ='{0}' or  REPLACE(t.FPHONE, '+', '') ='{0}') {1}", Mobile, OrgNumber);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "用户组织查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "用户未绑定组织！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("用户组织查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //更新商品上架
        internal string UpdateNmuber(Context ctx, string lstParams, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                string Number = "";
                string Grounding = "";
                JObject jParams = JObject.Parse(lstParams);
                JArray FBillEntry = JArray.Parse(jParams["data"].ToString());
                foreach (JObject List in FBillEntry)
                {
                    Number = List["Number"].ToString();
                    Grounding = List["Grounding"].ToString();
                    sql = string.Format(@"update T_BD_MATERIAL set F_QUDE_CHECKBOX = '{0}' where FNUMBER = '{1}'", Grounding, Number);
                    DBUtils.Execute(ctx, sql);
                }
                result["Result"] = true;
                result["Message"] = "更新成功！";
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("用户查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }


        //查询商家保证金，余额信息
        internal string QueryStore(Context ctx, string Mobile, string OrgNumber, string MerchantNumber, JObject result)
        {
            result["Result"] = false;
            try
            {
                long F_ORA_MULTIPLE = 1L;
                decimal F_ORA_AMOUNT = 0;
                decimal F_PUR_Amount = 0;
                string FUseOrgId = "";
                string F_ORA_MERCHANT = "";
                string MerchantName = "";
                string Currency = "";
                string SysMbol = "";
                string StafName = "";
                string Note = "";
                string CustomerNumber = "";
                string CustomerName = "";
                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    Mobile = string.Format(" and (REPLACE(t2.FPHONE, '-', '') ='{0}' or  REPLACE(t2.FPHONE, '+', '') ='{0}')", Mobile);
                }
                else
                {
                    Mobile = "";
                }
                if (!string.IsNullOrWhiteSpace(MerchantNumber))
                {
                    MerchantNumber = string.Format(" and t4.FNUMBER  = '{0}'", MerchantNumber);
                }
                else
                {
                    MerchantNumber = "";
                }

                //获取组织
                string SQL = string.Format(@"select t1.FORGID as FORGID,t.FID as F_ORA_MERCHANT,t4.FNUMBER as MerchantNumber,t3.FNAME as MerchantName,t14.FNAME  AS Currency,
                                            t12.FSYSMBOL AS SysMbol,isnull(t16.FNAME,'') as StafName,t4.F_QUDE_REMARK as Note,t18.FNUMBER as CustomerNumber, t17.FNAME as CustomerName   
                                            from QUDE_StoreEntity t 
                                            inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.F_QUDE_ORGID
                                            inner join T_SEC_user t2 on t2.FUSERID = t.F_QUDE_STOREFILE
                                            inner join QUDE_t_StoresFiles_L t3 on t3.FID = t.FID and t3.FLocaleID = 2052
                                            inner join QUDE_t_StoresFiles t4 on t4.FID = t3.FID
                                            INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t1.FORGID
                                            INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                            INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                            INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                            INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = 2052
                                            inner join T_BD_CUSTOMER t18 on t18.FCUSTID = t4.FCUSTOMERID
                                            inner join T_BD_CUSTOMER_L t17 on t17.FCUSTID = t18.FCUSTID and t17.FLocaleID = 2052
                                            left join V_BD_SALESMAN t15 on t15.fid = t4.F_QUDE_SUPPLIER
                                            left join V_BD_SALESMAN_L t16 on t16.fid = t15.fid  and t16.FLocaleID = 2052
                                                    where t1.FIsRights = 1  and t4.FDOCUMENTSTATUS = 'C' and t1.FNUMBER  = '{0}' {1} {2} ", OrgNumber, MerchantNumber, Mobile);
                DynamicObjectCollection dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    FUseOrgId = Convert.ToString(dynamicObjects.First()["FORGID"]);
                    F_ORA_MERCHANT = Convert.ToString(dynamicObjects.First()["F_ORA_MERCHANT"]);
                    MerchantName = Convert.ToString(dynamicObjects.First()["MerchantName"]);
                    MerchantNumber = Convert.ToString(dynamicObjects.First()["MerchantNumber"]);
                    Currency = Convert.ToString(dynamicObjects.First()["Currency"]);
                    SysMbol = Convert.ToString(dynamicObjects.First()["SysMbol"]);
                    StafName = Convert.ToString(dynamicObjects.First()["StafName"]);
                    Note = Convert.ToString(dynamicObjects.First()["Note"]);
                    CustomerNumber = Convert.ToString(dynamicObjects.First()["CustomerNumber"]);
                    CustomerName = Convert.ToString(dynamicObjects.First()["CustomerName"]);
                    SQL = string.Format("select  F_ORA_MULTIPLE from ora_t_Patformparameter where F_ORA_ORGID = '{0}'", FUseOrgId);
                    dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                    if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                    {
                        //保证金额度比例
                        F_ORA_MULTIPLE = Convert.ToInt64(dynamicObjects.First()["F_ORA_MULTIPLE"]);
                    }
                    //保证金
                    SQL = string.Format(@"SELECT  F_ORA_AMOUNT FROM ora_DepositSubmissionForm WHERE FUSEORGID = '{0}' AND F_ORA_MERCHANT = '{1}'", FUseOrgId, F_ORA_MERCHANT);
                    dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                    if (dynamicObjects != null && dynamicObjects.Count > 0)
                    {
                        F_ORA_AMOUNT = Convert.ToDecimal(dynamicObjects.First()["F_ORA_AMOUNT"]);
                    }
                    //竞价采购已成交金额
                    SQL = string.Format(@"select sum(FALLAMOUNT) as FALLAMOUNT from QUDE_BiddingPurchaseOrder where FTRANSACTIONS = '2' and F_QUDE_MERCHANT = '{0}' and FAPPLICATIONORGID = '{1}' and FCOLLECTIONIN = '1'", F_ORA_MERCHANT, FUseOrgId);
                    dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                    if (dynamicObjects != null && dynamicObjects.Count > 0)
                    {
                        F_PUR_Amount = Convert.ToDecimal(dynamicObjects.First()["FALLAMOUNT"]);
                    }
                    //可用余额
                    decimal FAVAILABLEBALANCE = (F_ORA_AMOUNT * F_ORA_MULTIPLE) - F_PUR_Amount;
                    JObject Data = new JObject();
                    Data.Add("MerchantNumber", MerchantNumber); //编码
                    Data.Add("MerchantName", MerchantName); //编码
                    Data.Add("AvailableBalance", FAVAILABLEBALANCE); //编码
                    Data.Add("Bond", F_ORA_AMOUNT); //编码
                    Data.Add("Currency", Currency); //编码 
                    Data.Add("SysMbol", SysMbol); //编码 
                    Data.Add("StafName", StafName); //编码 
                    Data.Add("Note", Note); //编码 
                    Data.Add("CustomerNumber", CustomerNumber); //编码 
                    Data.Add("CustomerName", CustomerName); //编码 
                    result["Result"] = true;
                    result["Message"] = "商家保证金，余额查询成功！";
                    result["Data"] = Data;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "商家查询失败！用户未绑定区域商家";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("商家查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        #region 商家用户明细
        internal string QueryUserEntry(Context ctx, string MerchantNumber, JObject result)
        {
            try
            {
                result["Result"] = false;
                string sql = string.Format(@"/*dialect*/select 
                                                        sec.FUSERACCOUNT as UserAccount,
                                                        sec.FName as UserName,
                                                        sec.FPHONE as Phone,
                                                        sec.FEmail as Email
                                                        from QUDE_t_StoresFiles t
                                                        inner join QUDE_StoreEntity Store on Store.FID = t.FID
                                                        inner join T_SEC_user sec on sec.FUSERID = Store.F_QUDE_STOREFILE
                                                        where t.FNUMBER = '{0}'", MerchantNumber);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "商家用户详情成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "商家用户完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("商家用户失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 商家信息列表
        internal string QueryStoreList(Context ctx, string OrgNumber, string MerchantNumber, string MerchantName, string StafPhone, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("/*dialect*/ SELECT MerchantNumber, MerchantName,OrgNumber,OrgName,Status,FCreateDate, Currency, SysMbol, StafName,StafPhone, Note, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FCreateDate DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@" /*dialect*/( select 
                                        t.FID as F_ORA_MERCHANT,
                                        t.FNUMBER as MerchantNumber,
                                        t3.FNAME as MerchantName,
                                        t1.FNUMBER as OrgNumber,
                                        t2.FNAME as OrgName,
                                        case when t.FDOCUMENTSTATUS = 'C' then '已审核'
                                        when t.FDOCUMENTSTATUS = 'D' then '重新审核' 
                                        when t.FDOCUMENTSTATUS = 'B' then '审核中' 
                                        when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
                                        CONVERT(varchar(30),t.FCreateDate,20)  as FCreateDate,
                                        t14.FNAME  AS Currency,
                                        t12.FSYSMBOL AS SysMbol,
                                        isnull(t16.FNAME,'') as StafName,
                                        isnull(secl.FPHONE,'') as StafPhone,
                                        t.F_QUDE_REMARK as Note   
                                        from QUDE_t_StoresFiles t 
                                        inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FUSEORGID
                                        inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLOCALEID = 2052
                                        inner join QUDE_t_StoresFiles_L t3 on t3.FID = t.FID and t3.FLocaleID = 2052
                                        INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t1.FORGID
                                        INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                        INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                        INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                        INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = 2052
                                        left join V_BD_SALESMAN t15 on t15.fid = t.F_QUDE_SUPPLIER
                                        left join V_BD_SALESMAN_L t16 on t16.fid = t15.fid  and t16.FLocaleID = 2052
                                        left join T_SEC_user secl on secl.FNAME = t16.FNAME
                                        where t1.FIsRights = 1

                                        ");
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND  t1.FNUMBER = @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                if (!string.IsNullOrWhiteSpace(MerchantNumber))
                {
                    MerchantNumber = "%" + MerchantNumber + "%";
                    sbSql.AppendLine(" AND  t.FNUMBER LIKE @MerchantNumber ");
                    lstParam.Add(new SqlParam("@MerchantNumber", KDDbType.String, MerchantNumber));
                }
                if (!string.IsNullOrWhiteSpace(MerchantName))
                {
                    MerchantName = "%" + MerchantName + "%";
                    sbSql.AppendLine(" AND  t3.FNAME LIKE @MerchantName ");
                    lstParam.Add(new SqlParam("@MerchantName", KDDbType.String, MerchantName));
                }
                if (!string.IsNullOrWhiteSpace(StafPhone))
                {
                    sbSql.AppendLine(" AND  isnull(secl.FPHONE,'') = @StafPhone ");
                    lstParam.Add(new SqlParam("@StafPhone", KDDbType.String, StafPhone));
                }
                sbSql.AppendLine(" ) t ");
                sbSql.AppendFormat("SELECT FIDENTITYID,MerchantNumber, MerchantName,OrgNumber,OrgName,Status,FCreateDate, Currency, SysMbol, StafName,StafPhone, Note  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        JArray XData = JArray.FromObject(Datas);
                        foreach (JObject cardData in XData)
                        {
                            JObject Entry = new JObject();
                            Entry.Add("Result", false);
                            Entry.Add("Message", "");
                            Entry.Add("Data", string.Empty);

                            MerchantNumber = cardData["MerchantNumber"].ToString();
                            this.QueryUserEntry(ctx, MerchantNumber, Entry);
                            cardData.Add("Entry", Entry["Data"]);
                        }
                        Data.Add("Datas", XData);
                        result["Result"] = true;
                        result["Message"] = "商家列表信息查询成功！";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "商家列表信息查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "商家列表信息查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("商家列表信息查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 经纪人提成列表
        internal string AccountManagerList(Context ctx, string OrgNumber, string StafPhone, string StafName, string StatisticalDate, string To, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                //当前执行日期
                DateTime date = DateTime.Now;
                DateTime startMonth = date.AddDays(1 - date.Day);  //本月月初
                DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);  //本月月末


                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);
                sbSql.AppendLine("/*dialect*/ SELECT BillNo, StatisticalDate,ToDate,Status,AreaName,ApprovedDate, TotalCommission, ProfitMargin, TotalSales,TotalPurAmount, SalesProfit,ProcurementCommission, SalesCommission,ProfitCommission,AllCommission,Currency,SysMbol,StafPhone,StafName,");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY ApprovedDate DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@" /*dialect*/( select 
                                                t.FBILLNO BillNo,
                                                isnull(CONVERT(varchar(30),t.FBDate,23),'') StatisticalDate,
                                                isnull(CONVERT(varchar(30),t.FEDate,23),'')  ToDate,
                                                case when t.FDOCUMENTSTATUS = 'C' then '已审核'
                                                when t.FDOCUMENTSTATUS = 'D' then '重新审核' 
                                                when t.FDOCUMENTSTATUS = 'B' then '审核中' 
                                                when t.FDOCUMENTSTATUS = 'A' then '创建' else '暂存' end as Status,
                                                t2.FNAME AreaName,
                                                isnull(CONVERT(varchar(30),t.F_QUDE_AuditDate,20),'') ApprovedDate,
                                                FTotalCommission TotalCommission,
                                                FProfitMargin ProfitMargin,
                                                FTotalSales TotalSales,
                                                FTotalPurAmount TotalPurAmount,
                                                FSalesProfit SalesProfit,
                                                FProcurementCommission ProcurementCommission,
                                                FSalesCommission SalesCommission,
                                                FProfitCommission ProfitCommission,
                                                FAllCommission AllCommission,
                                                t14.FNAME   Currency,
                                                t12.FSYSMBOL  SysMbol,
                                                isnull(secl.FPHONE,'') as StafPhone,
                                                t16.FNAME AS StafName
                                                from QUDE_BrokerCommissionTable t
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FCreateOrgId
                                                inner join T_ORG_ORGANIZATIONS_L t2 on t2.FORGID = t1.FORGID and t2.FLocaleID = 2052
                                                inner join V_BD_SALESMAN t15 on t15.fid = t.FBroker
                                                INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t1.FORGID
                                                INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                                INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = 2052
                                                inner join V_BD_SALESMAN_L t16 on t16.fid = t15.fid  and t16.FLocaleID = 2052
                                                left join T_SEC_user secl on secl.FNAME = t16.FNAME
                                                WHERE 1=1
                                        ");
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND  t1.FNUMBER = @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                if (!string.IsNullOrWhiteSpace(StafPhone))
                {
                    sbSql.AppendLine(" AND  isnull(secl.FPHONE,'') = @StafPhone ");
                    lstParam.Add(new SqlParam("@StafPhone", KDDbType.String, StafPhone));
                }
                if (!string.IsNullOrWhiteSpace(StafName))
                {
                    StafName = "%" + StafName + "%";
                    sbSql.AppendLine(" AND  t16.FNAME LIKE @StafName ");
                    lstParam.Add(new SqlParam("@StafName", KDDbType.String, StafName));
                }
                if (!string.IsNullOrWhiteSpace(StatisticalDate))
                {

                    sbSql.AppendLine(" AND  t.FBDate >= @StatisticalDate ");
                    lstParam.Add(new SqlParam("@StatisticalDate", KDDbType.String, StatisticalDate));
                }
                if (!string.IsNullOrWhiteSpace(To))
                {
                    sbSql.AppendLine(" AND  t.FEDate <= @To ");
                    lstParam.Add(new SqlParam("@To", KDDbType.String, To));
                }
                DateTime ToS = Convert.ToDateTime(To);
                DateTime StatisticalDateS = Convert.ToDateTime(StatisticalDate);
                TimeSpan diff = ToS - date;
                TimeSpan diffs = StatisticalDateS - date;
                
                int diffDays = diff.Days;
                int diffDayss = diffs.Days;
                if (diffDays >= 0 && diffDayss <= 0)
                {
                    sbSql.AppendLine(" union all ");
                    sbSql.AppendFormat(@"select 
                                        t3.FNAME + '-' + '{2}' BillNo,
                                        '{0}' StatisticalDate,
                                        '{1}' ToDate,
                                        '已审核' Status,
                                        t5.FNAME AreaName,
                                        '{1}' ApprovedDate,
                                        t1.FTotalCommission FTotalCommission,
                                        t1.FProfitMargin FProfitMargin,
                                        ISNULL(FTotalSales, 0) AS TotalSales,
                                        isnull(FTotalPurAmount, 0) as TotalPurAmount,
                                        isnull(FSalesProfit, 0) AS SalesProfit,
                                        t1.FTotalCommission * isnull(FTotalPurAmount, 0) ProcurementCommission,
                                        t1.FTotalCommission * ISNULL(FTotalSales, 0)  SalesCommission,
                                        t1.FProfitMargin * isnull(FSalesProfit, 0)  ProfitCommission,
                                        t1.FTotalCommission * isnull(FTotalPurAmount, 0) + t1.FTotalCommission * ISNULL(FTotalSales, 0) + t1.FProfitMargin * isnull(FSalesProfit, 0)  AllCommission,
                                        t14.FNAME   Currency,
                                        t12.FSYSMBOL  SysMbol,
                                        isnull(secl.FPHONE, '') as StafPhone,
                                        t3.FNAME AS StafName
                                        from V_BD_SALESMAN t
                                        inner
                                        join T_BD_OPERATORENTRY t1 on t1.FSTAFFID = t.FSTAFFID and t.FBizOrgId = t1.FBizOrgId
                                        inner join T_ORG_ORGANIZATIONS t4 on t4.FORGID = t1.FBizOrgId
                                        inner join T_ORG_ORGANIZATIONS_L t5 on t5.FORGID = t4.FORGID and t5.FLOCALEID = 2052
                                        inner join V_BD_SALESMAN_L t3 on t3.fid = t.fid  and t3.FLocaleID = 2052
                                        INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID = t4.FORGID
                                        INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID = t10.FACCTSYSTEMID AND t13.FISDEFAULT = 1
                                        INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY = t11.FACCTPOLICYID
                                        INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID = t11.FCURRENCYID
                                        INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = 2052
                                        left join T_SEC_user secl on secl.FNAME = t3.FNAME
                                        LEFT join(select sum(t.F_QUDE_SALEAMOUNT) as FTotalSales, t2.F_QUDE_SUPPLIER as F_QUDE_SUPPLIER
                                                                                        from ora_CompetitiveTransaction t
                                                                                        inner
                                                                                        join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.F_PIYZ_ORGID

                                                                                  inner
                                                                                        join QUDE_t_StoresFiles t2 on t2.FID = t.F_QUDE_SALER
                                                                                        where t.F_PIYZ_BILLSTATUS = 2
                                                                                        and t.F_QUDE_Date >= '{0}' and t.F_QUDE_Date <= '{1}'
                                                                                        group by t2.F_QUDE_SUPPLIER)TotalSales on TotalSales.F_QUDE_SUPPLIER = t.fid
                                        LEFT JOIN(select sum(t.F_QUDE_PurAmount) as FTotalPurAmount, t2.F_QUDE_SUPPLIER as F_QUDE_SUPPLIER
                                                                                        from ora_CompetitiveTransaction t
                                                                                        inner
                                                                                        join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.F_PIYZ_ORGID

                                                                                  inner
                                                                                        join QUDE_t_StoresFiles t2 on t2.FID = t.F_QUDE_Buy
                                                                                        where t.F_PIYZ_BILLSTATUS = 2
                                                                                        and t.F_QUDE_Date >= '{0}' and t.F_QUDE_Date <= '{1}'
                                                                                        group by t2.F_QUDE_SUPPLIER)TotalPur ON TotalPur.F_QUDE_SUPPLIER = t.fid
                                        LEFT JOIN(select sum(t.F_QUDE_PurAmount - t.F_QUDE_SALEAMOUNT) as FSalesProfit, t2.F_QUDE_SUPPLIER as F_QUDE_SUPPLIER
                                                                                        from ora_CompetitiveTransaction t
                                                                                        inner
                                                                                        join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.F_PIYZ_ORGID

                                                                                  inner
                                                                                        join QUDE_t_StoresFiles t2 on t2.FID = t.F_QUDE_SALER
                                                                                        where t.F_PIYZ_BILLSTATUS = 2
                                                                                        and t.F_QUDE_Date >= '{0}' and t.F_QUDE_Date <= '{1}'
                                                                                        group by t2.F_QUDE_SUPPLIER)SalesProfit ON SalesProfit.F_QUDE_SUPPLIER = T.fid

                                        where t1.FOPERATORTYPE = 'XSY' and t1.FTotalCommission > 0 and t1.FProfitMargin > 0
                                         ", startMonth.ToString("yyyy-MM-dd"), endMonth.ToString("yyyy-MM-dd"), startMonth.ToString("yyyyMM"));
                    if (!string.IsNullOrWhiteSpace(OrgNumber))
                    {
                        sbSql.AppendLine(" AND  t4.FNUMBER = @OrgNumbers ");
                        lstParam.Add(new SqlParam("@OrgNumbers", KDDbType.String, OrgNumber));
                    }
                    if (!string.IsNullOrWhiteSpace(StafPhone))
                    {
                        sbSql.AppendLine(" AND  isnull(secl.FPHONE,'') = @StafPhones ");
                        lstParam.Add(new SqlParam("@StafPhones", KDDbType.String, StafPhone));
                    }
                    if (!string.IsNullOrWhiteSpace(StafName))
                    {
                        sbSql.AppendLine(" AND  t3.FNAME LIKE @StafNameS ");
                        lstParam.Add(new SqlParam("@StafNameS", KDDbType.String, StafName));
                    }
                }

                sbSql.AppendLine(" ) t ");
                sbSql.AppendFormat("SELECT FIDENTITYID,BillNo, StatisticalDate,ToDate,Status,AreaName,ApprovedDate, TotalCommission, ProfitMargin, TotalSales,TotalPurAmount, SalesProfit,ProcurementCommission, SalesCommission,ProfitCommission,AllCommission,Currency,SysMbol,StafPhone,StafName  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "经纪人提成列表查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "经纪人提成列表查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "经纪人提成列表查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("经纪人提成列表查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 商品数据查询
        internal string MaterialInfo(Context ctx, string Number, string OrgNumber, string ChineseName, string EnglishName, string Year, string Area, string Capacity, string MinimumOrder, string GPurchaseQuantity, string GSalesQuantity, string LPurchaseQuantity, string LSalesQuantity, string Grounding, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("SELECT ORGNUMBER, ORGNAME, NUMBER, NAME, WINEBASE, WINEBASENAME, REGIONS,COUNTRY,STYLE,SCORE,NOTE,WINEYEAR,SIZE,ALCOHOLS,STOREUNITID,AUXUNITID,XCONVERTNUMERATOR, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY ORGNUMBER, NUMBER DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@"(select  
                                    t7.FNUMBER as ORGNUMBER,
                                    t8.FNAME as ORGNAME,
                                    t1.FNUMBER as NUMBER ,
                                    t2.FNAME as NAME,
                                    t3.FNUMBER as WINEBASE,
                                    t4.FNAME as WINEBASENAME,
                                    t3.FREGIONS AS REGIONS,
                                    t5.FDATAVALUE as COUNTRY,
                                    t6.FDATAVALUE as STYLE,
                                    t1.FSCORE as SCORE,
                                    t1.F_ORA_MEMO as NOTE,
                                    t9.FDATAVALUE as WINEYEAR,
                                    isnull(t10.FDATAVALUE,'') as SIZE,
                                    isnull(t11.FDATAVALUE,'') as ALCOHOLS,
                                    t14.FNAME as STOREUNITID,
                                    t16.FNAME as AUXUNITID,
                                    t17.FXCONVERTNUMERATOR  as XCONVERTNUMERATOR
                                    from T_BD_MATERIAL t1
                                    inner join T_BD_MATERIAL_L t2 on t2.FMATERIALID = t1.FMATERIALID and t2.FLOCALEID  = @FLocaleId
                                    left join ora_t_Cust100034 t3 on t3.FID = t1.FWINEBASE1
                                    left join ora_t_Cust100034_L t4 on t4.FID = t3.FID  and t4.FLOCALEID  = @FLocaleId
                                    left join T_BAS_ASSISTANTDATAENTRY_L t5 on t5.FENTRYID = t3.FCOUNTRY and t5.FLOCALEID  = @FLocaleId
                                    left join T_BAS_ASSISTANTDATAENTRY_L t6 on t6.FENTRYID = t3.FSTYLE and t6.FLOCALEID  = @FLocaleId
                                    left join T_ORG_ORGANIZATIONS t7 on t7.FORGID = t1.FUSEORGID
                                    left join T_ORG_ORGANIZATIONS_L t8 on t8.FORGID = t7.FORGID  and t8.FLOCALEID = @FLocaleId 
                                    left join T_BAS_ASSISTANTDATAENTRY_L t9 on t9.FENTRYID = t1.FWINEYEAR1 and t9.FLOCALEID  = @FLocaleId
                                    left join T_BAS_ASSISTANTDATAENTRY_L t10 on t10.FENTRYID = t1.FSIZE and t10.FLOCALEID  = @FLocaleId
                                    left join T_BAS_ASSISTANTDATAENTRY_L t11 on t11.FENTRYID = t1.FALCOHOLS and t11.FLOCALEID  = @FLocaleId
                                    left join t_BD_MaterialStock t12 on t12.FMATERIALID = t1.FMATERIALID
                                    left join T_BD_UNIT t13 on t13.FUNITID = t12.FSTOREUNITID
                                    left join T_BD_UNIT_L t14 on t14.FUNITID = t13.FUNITID and t14.FLOCALEID = @FLocaleId
                                    left join T_BD_UNIT t15 on t15.FUNITID = t12.FAUXUNITID
                                    left join T_BD_UNITCONVERTRATE t17 ON t17.FUNITID = t15.FUNITID
                                    left join T_BD_UNIT_L t16 on t16.FUNITID = t15.FUNITID and t16.FLOCALEID = @FLocaleId
                                    left join (select  sum(FPURCHASESOLD) as FPURCHASESOLD,FWINECODE from QUDE_PurchaseOrderEntry T 
									INNER JOIN QUDE_BiddingPurchaseOrder T1 ON T1.FID = T.FID AND FTRANSACTIONS = 1
									GROUP BY FWINECODE)PUR ON PUR.FWINECODE = T1.FMATERIALID
								    left join (select  sum(FBOTTLESSOLD) as FBOTTLESSOLD,FWINECODE from QUDE_Sale_OrderEntry T 
									INNER JOIN QUDE_Bidding_SalesOrder T1 ON T1.FID = T.FID AND FTRANSACTIONS = 1
									GROUP BY FWINECODE)SAL ON SAL.FWINECODE = T1.FMATERIALID
                                    where t1.FDOCUMENTSTATUS = 'C'");
                if (!string.IsNullOrWhiteSpace(Number))
                {
                    sbSql.AppendLine(" AND  T1.FNUMBER = @Number ");
                    lstParam.Add(new SqlParam("@Number", KDDbType.String, Number));
                }
                if (!string.IsNullOrWhiteSpace(Grounding))
                {
                    sbSql.AppendLine(" AND  T1.F_QUDE_CHECKBOX = @Grounding ");
                    lstParam.Add(new SqlParam("@Grounding", KDDbType.String, Grounding));
                }

                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND T7.FNUMBER =  @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                //string  , string EnglishName, string Year, string Area, string Capacity, string MinimumOrder, string PurchaseQuantity, string SalesQuantity,
                if (!string.IsNullOrWhiteSpace(ChineseName))
                {
                    ChineseName = "%" + ChineseName + "%";
                    sbSql.AppendLine(" AND t4.F_ORA_MULLANGTEXT LIKE  @ChineseName ");
                    lstParam.Add(new SqlParam("@ChineseName", KDDbType.String, ChineseName));
                }

                if (!string.IsNullOrWhiteSpace(EnglishName))
                {
                    EnglishName = "%" + EnglishName + "%";
                    sbSql.AppendLine(" AND t3.FENGLISH LIKE  @EnglishName ");
                    lstParam.Add(new SqlParam("@EnglishName", KDDbType.String, EnglishName));
                }

                if (!string.IsNullOrWhiteSpace(Year))
                {
                    Year = "%" + Year + "%";
                    sbSql.AppendLine(" AND t9.FDATAVALUE LIKE  @Year ");
                    lstParam.Add(new SqlParam("@Year", KDDbType.String, Year));
                }

                if (!string.IsNullOrWhiteSpace(Area))
                {
                    Area = "%" + Area + "%";
                    sbSql.AppendLine(" AND t3.FREGIONS LIKE  @Area ");
                    lstParam.Add(new SqlParam("@Area", KDDbType.String, Area));
                }

                if (!string.IsNullOrWhiteSpace(Capacity))
                {
                    Capacity = "%" + Capacity + "%";
                    sbSql.AppendLine(" AND t10.FDATAVALUE LIKE  @Capacity ");
                    lstParam.Add(new SqlParam("@Capacity", KDDbType.String, Capacity));
                }

                if (!string.IsNullOrWhiteSpace(MinimumOrder))
                {
                    MinimumOrder = "%" + MinimumOrder + "%";
                    sbSql.AppendLine(" AND t16.FNAME LIKE  @MinimumOrder ");
                    lstParam.Add(new SqlParam("@MinimumOrder", KDDbType.String, MinimumOrder));
                }

                if (!string.IsNullOrWhiteSpace(GPurchaseQuantity))
                {
                    sbSql.AppendLine(" AND PUR.FPURCHASESOLD >= @GPurchaseQuantity ");
                    lstParam.Add(new SqlParam("@GPurchaseQuantity", KDDbType.String, GPurchaseQuantity));
                }
                if (!string.IsNullOrWhiteSpace(LPurchaseQuantity))
                {
                    sbSql.AppendLine("AND PUR.FPURCHASESOLD <= @LPurchaseQuantity ");
                    lstParam.Add(new SqlParam("@LPurchaseQuantity", KDDbType.String, LPurchaseQuantity));
                }

                if (!string.IsNullOrWhiteSpace(GSalesQuantity))
                {
                    sbSql.AppendLine(" AND SAL.FBOTTLESSOLD >= @GSalesQuantity");
                    lstParam.Add(new SqlParam("@GSalesQuantity", KDDbType.String, GSalesQuantity));
                }
                if (!string.IsNullOrWhiteSpace(LSalesQuantity))
                {
                    sbSql.AppendLine(" AND SAL.FBOTTLESSOLD <= @LSalesQuantity");
                    lstParam.Add(new SqlParam("@LSalesQuantity", KDDbType.String, LSalesQuantity));
                }


                sbSql.AppendLine(" ) t ");//WHERE TI.FBASEQTY > 0

                sbSql.AppendFormat("SELECT FIDENTITYID,  ORGNUMBER, ORGNAME, NUMBER, NAME, WINEBASE, WINEBASENAME, REGIONS,COUNTRY,STYLE,SCORE,NOTE,WINEYEAR,SIZE,ALCOHOLS,STOREUNITID,AUXUNITID,XCONVERTNUMERATOR  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "产品数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "产品数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "产品数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("产品数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 查询酒款信息列表查询
        internal string WinePaymentInfo(Context ctx, int iPageSize, int iPageNum, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"/*dialect*/select * from (
                                               select 
                                                    ROW_NUMBER() OVER (ORDER BY CONVERT(varchar(100),t.FMODIFYDATE , 120) DESC) AS FIDENTITYID,
                                                    t.FNUMBER as FNUMBER,
                                                    t1.FNAME as FNAME,
                                                    t1.F_ORA_MULLANGTEXT as F_ORA_MULLANGTEXT,
                                                    t.FENGLISH as FENGLISH,
                                                    t.FREGIONS as FREGIONS,
                                                    t2.FDATAVALUE as FCOUNTRY,
                                                    t3.FDATAVALUE as FSTYLE,
                                                    t.FDOCUMENTSTATUS as FDOCUMENTSTATUS
                                                    from 
                                                    ora_t_Cust100034 t
                                                    inner join ora_t_Cust100034_L t1 on t1.FID = t.FID and t1.FLocaleID = 2052
                                                    left join T_BAS_ASSISTANTDATAENTRY_L t2 on t2.FENTRYID = t.FCOUNTRY and t2.FLOCALEID  = 2052
                                                    left join T_BAS_ASSISTANTDATAENTRY_L t3 on t3.FENTRYID = t.FSTYLE and t3.FLOCALEID  = 2052 
                                                    where t.FDOCUMENTSTATUS = 'C') t
                                                where  t.FIDENTITYID between {0} and {1}", ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize);

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "查询酒款信息列表查询成功！";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "查询酒款信息列表查询，数据为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("查询酒款信息列表查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 实时竞价列表
        internal string QueryPurSalesOrder(Context ctx, string Mobile, string OrgNumber, string Year, string Capacity, string MinimumOrder, string GPurchaseQuantity, string GSalesQuantity, string LPurchaseQuantity, string LSalesQuantity, string MaterialName, string GPurchasePrice, string GSalesPrice, string LPurchasePrice, string LSalesPrice, string OrderBy, string ProductArea, string WineNumber, string Type, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                string sqla = "";
                string sqlb = "";
                string sqlc = "";
                string sqld = "";
                string sqle = "";
                string sqlf = "";
                string sqlg = "";
                string sqlh = "";
                string sqli = "";
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);
                if (!string.IsNullOrWhiteSpace(GPurchaseQuantity))
                {
                    sqla = string.Format("AND cg.FPURCHASESOLD >= '{0}'", GPurchaseQuantity);
                }
                if (!string.IsNullOrWhiteSpace(LPurchaseQuantity))
                {
                    sqlb = string.Format("AND cg.FPURCHASESOLD <= '{0}'", LPurchaseQuantity);
                }

                if (!string.IsNullOrWhiteSpace(GSalesQuantity))
                {
                    sqlc = string.Format("AND xs.FBOTTLESSOLD >= '{0}'", GSalesQuantity);
                }
                if (!string.IsNullOrWhiteSpace(LSalesQuantity))
                {
                    sqld = string.Format("AND xs.FBOTTLESSOLD <= '{0}'", LSalesQuantity);
                }
                //价格
                if (!string.IsNullOrWhiteSpace(GPurchasePrice))
                {
                    sqlf = string.Format("AND ISNULL(cg.PurAmount,0) >= '{0}'", GPurchasePrice);
                }
                if (!string.IsNullOrWhiteSpace(LPurchasePrice))
                {
                    sqlg = string.Format("AND ISNULL(cg.PurAmount,0) <= '{0}'", LPurchasePrice);
                }

                if (!string.IsNullOrWhiteSpace(GSalesPrice))
                {
                    sqlh = string.Format("AND ISNULL(xs.SaleAmount,0) >= '{0}'", GSalesPrice);
                }
                if (!string.IsNullOrWhiteSpace(LSalesPrice))
                {
                    sqli = string.Format("AND ISNULL(xs.SaleAmount,0) <= '{0}'", LSalesPrice);
                }


                if (!string.IsNullOrWhiteSpace(WineNumber))
                {
                    sqle = string.Format("AND t3.FNUMBER = '{0}'", WineNumber);
                }
                if (!string.IsNullOrWhiteSpace(ProductArea))
                {
                    ProductArea = string.Format("AND t3.FREGIONS = '{0}'", ProductArea);
                }

                sbSql.AppendLine("/*dialect*/SELECT Material,MaterialId,FMODIFYDATE,PurAmount,SaleAmount,SysMbol,FPURCHASESOLD,FBOTTLESSOLD, ");
                if (OrderBy == "0")
                {
                    sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY  FMODIFYDATE desc) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                }
                else if (OrderBy == "1")
                {
                    sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY case when SaleAmount > 0 then 1 else 2  end ,  FMODIFYDATE desc) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                }
                else if (OrderBy == "2")
                {
                    sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY case when PurAmount > 0 then 1 else 2  end ,  FMODIFYDATE desc) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                }
                sbSql.AppendFormat(@"/*dialect*/(
                                                    select  
                                                    MATERIAL.FNAME   as Material,
                                                     t.FMATERIALID  as MaterialId,
                                                    case when cg.FMODIFYDATE is null and xs.FMODIFYDATE is not null then CONVERT(varchar(100), xs.FMODIFYDATE, 120) 
                                                    when xs.FMODIFYDATE is null and cg.FMODIFYDATE is not null  then CONVERT(varchar(100), cg.FMODIFYDATE, 120) 
                                                    when xs.FMODIFYDATE is not null and cg.FMODIFYDATE is not null and xs.FMODIFYDATE > cg.FMODIFYDATE  then CONVERT(varchar(100), xs.FMODIFYDATE, 120)
                                                    when xs.FMODIFYDATE is not null and cg.FMODIFYDATE is not null and xs.FMODIFYDATE <= cg.FMODIFYDATE  then CONVERT(varchar(100), cg.FMODIFYDATE, 120)
                                                    else '1900-11-15 15:12:07'  end  as FMODIFYDATE,
                                                    ISNULL(cg.PurAmount,0) AS PurAmount,
                                                    ISNULL(xs.SaleAmount,0) AS SaleAmount,
                                                    case when cg.MaterialId is null and xs.MaterialId is not null then xs.SysMbol 
                                                    when xs.MaterialId is null and cg.MaterialId is not null then cg.SysMbol 
                                                    when xs.MaterialId is not null and cg.MaterialId is not null then cg.SysMbol else '' end  as SysMbol,
                                                    isnull(cg.FPURCHASESOLD,0) as FPURCHASESOLD,
                                                    isnull(xs.FBOTTLESSOLD,0)  as FBOTTLESSOLD
                                                    from T_BD_MATERIAL t 
                                                    inner join T_BD_MATERIAL_L MATERIAL on MATERIAL.FMATERIALID = t.FMATERIALID AND MATERIAL.FLOCALEID = 2052
                                                    INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t.FUSEORGID	AND t8.FNUMBER =  '{0}'
                                                    left join ora_t_Cust100034 t3 on t3.FID = t.FWINEBASE1
                                                    left join T_BAS_ASSISTANTDATAENTRY_L t9 on t9.FENTRYID = t.FWINEYEAR1 and t9.FLOCALEID  = 2052
                                                    left join T_BAS_ASSISTANTDATAENTRY_L t10 on t10.FENTRYID = t.FSIZE and t10.FLOCALEID  = 2052
                                                    left join T_BAS_ASSISTANTDATAENTRY_L LXL on LXL.FENTRYID = t3.FSTYLE and LXL.FLOCALEID  = 2052
                                                    left join t_BD_MaterialStock t12 on t12.FMATERIALID = t.FMATERIALID
                                                    left join T_BD_UNIT t15 on t15.FUNITID = t12.FAUXUNITID
                                                    left join T_BD_UNITCONVERTRATE t17 ON t17.FUNITID = t15.FUNITID
                                                    left join T_BD_UNIT_L t16 on t16.FUNITID = t15.FUNITID and t16.FLOCALEID = 2052

                                                    left join  (select 
                                                    T5.FNAME AS Material,
                                                    t2.FWINECODE AS MaterialId,
                                                     max(t1.FMODIFYDATE) AS FMODIFYDATE,
                                                    t2.FPURCHASEPRICE AS PurAmount,
                                                    max(t2.FPURCHASESOLD) as FPURCHASESOLD,
                                                    t12.FSYSMBOL AS SysMbol
                                                    FROM
                                                    (
                                                    SELECT
                                                    t2.FWINECODE AS MaterialId,
                                                    MAX ( t2.FPURCHASEPRICE ) AS BidPrice
                                                    
                                                    FROM
                                                    QUDE_BiddingPurchaseOrder t1
                                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t1.FID = t2.FID and t1.FDOCUMENTSTATUS = 'C' 
                                                    INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                                    INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t9.FID
                                                    INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE                                      
                                                    WHERE
                                                    FTRANSACTIONS = 1 
                                                    GROUP BY
                                                    FWINECODE
                                                    ) t
                                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t.MaterialId = t2.FWINECODE 
	                                                    AND t.BidPrice = t2.FPURCHASEPRICE
                                                    INNER JOIN QUDE_BiddingPurchaseOrder t1 ON t1.FID = t2.FID 
                                                    INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	AND t8.FNUMBER =  '{0}'
                                                    INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE and t4.F_QUDE_CHECKBOX = 1
                                                    INNER JOIN T_BD_MATERIAL_L T5 ON T5.FMATERIALID = T4.FMATERIALID AND T5.FLOCALEID = @FLocaleId
                                                    INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
                                                    INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                    INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                    INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                                    group by T5.FNAME,t2.FWINECODE,t2.FPURCHASEPRICE,t12.FSYSMBOL)cg on cg.MaterialId = t.FMATERIALID 
                                                                                               
                                                    left join (
                                                    select
                                                    T5.FNAME AS Material,
                                                    t2.FWINECODE AS MaterialId,
                                                    max(t1.FMODIFYDATE)AS FMODIFYDATE,
                                                    t2.FSELLINGPRICE as SaleAmount,
                                                    max(t2.FBOTTLESSOLD) as FBOTTLESSOLD,
                                                    t12.FSYSMBOL AS SysMbol
                                                    FROM
                                                    (
                                                    SELECT
                                                    t2.FWINECODE AS MaterialId,
                                                    MIN ( t2.FSELLINGPRICE ) AS OfferPrice
                                                    
                                                    FROM
                                                    QUDE_Bidding_SalesOrder t1
                                                    INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID and t1.FDOCUMENTSTATUS = 'C'
                                                    INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                                    INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE 
                                                    WHERE
                                                    FTRANSACTIONS = 1
                                                    GROUP BY
                                                    FWINECODE
                                                    ) t
                                                    INNER JOIN QUDE_Sale_OrderEntry t2 ON t.MaterialId = t2.FWINECODE 
                                                    AND t.OfferPrice = t2.FSELLINGPRICE
                                                    INNER JOIN QUDE_Bidding_SalesOrder t1 ON t1.FID = t2.FID 
                                                    INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	AND t8.FNUMBER =  '{0}'
                                                    INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE and t4.F_QUDE_CHECKBOX = 1
                                                    INNER JOIN T_BD_MATERIAL_L T5 ON T5.FMATERIALID = T4.FMATERIALID AND T5.FLOCALEID = @FLocaleId
                                                    INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
                                                    INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                    INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                    INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID 
                                                    group by T5.FNAME,t2.FWINECODE,t2.FSELLINGPRICE,t12.FSYSMBOL )xs on xs.MaterialId = t.FMATERIALID   
                                                    where t.F_QUDE_CHECKBOX = 1 {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}
                                                ", OrgNumber, sqla, sqlb, sqlc, sqld, sqle, sqlf, sqlg, sqlh, sqli, ProductArea);
                if (!string.IsNullOrWhiteSpace(MaterialName))
                {
                    MaterialName = "%" + MaterialName.Replace("-", " ") + "%";
                    sbSql.AppendLine(" and  REPLACE(MATERIAL.FNAME, '-', ' ') LIKE  @MaterialName");
                    lstParam.Add(new SqlParam("@MaterialName", KDDbType.String, MaterialName));
                }
                if (!string.IsNullOrWhiteSpace(Year))
                {
                    Year = "%" + Year + "%";
                    sbSql.AppendLine(" AND t9.FDATAVALUE LIKE  @Year ");
                    lstParam.Add(new SqlParam("@Year", KDDbType.String, Year));
                }

                if (!string.IsNullOrWhiteSpace(Capacity))
                {
                    Capacity = "%" + Capacity + "%";
                    sbSql.AppendLine(" AND t10.FDATAVALUE LIKE  @Capacity ");
                    lstParam.Add(new SqlParam("@Capacity", KDDbType.String, Capacity));
                }

                if (!string.IsNullOrWhiteSpace(MinimumOrder))
                {
                    MinimumOrder = "%" + MinimumOrder + "%";
                    sbSql.AppendLine(" AND t16.FNAME LIKE  @MinimumOrder ");
                    lstParam.Add(new SqlParam("@MinimumOrder", KDDbType.String, MinimumOrder));
                }
                if (!string.IsNullOrWhiteSpace(Type))
                {
                    sbSql.AppendLine(" AND ISNULL(LXL.FDATAVALUE,0) =  @Type ");
                    lstParam.Add(new SqlParam("@Type", KDDbType.String, Type));
                }


                sbSql.AppendLine(" )jk ");
                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));
                sbSql.AppendFormat(@"/*dialect*/select FIDENTITYID,t4.FNUMBER AS materialid,Material,PurAmount,SaleAmount,ISNULL(SysMbol,'') as SysMbol,case when (TS.MaterialId IS  NOT NULL AND Td.MaterialId IS NULL) THEN 1 
                      WHEN (TS.MaterialId IS  NULL AND Td.MaterialId IS NOT NULL) THEN 2 WHEN (TS.MaterialId IS NOT NULL AND Td.MaterialId IS NOT NULL) THEN 3 ELSE 0 END AS IsFaBu,FPURCHASESOLD,FBOTTLESSOLD,ISNULL(LXL.FDATAVALUE,0) AS Type
                     from (SELECT  FIDENTITYID, Material, MaterialId, PurAmount, SaleAmount, SysMbol,FPURCHASESOLD,FBOTTLESSOLD FROM {0}
                where FIDENTITYID between {1}
                and {2})t INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t.MaterialId
                     left join ora_t_Cust100034 LX on LX.FID = T4.FWINEBASE1
                     left join T_BAS_ASSISTANTDATAENTRY_L LXL on LXL.FENTRYID = LX.FSTYLE and LXL.FLOCALEID  = 2052
                     LEFT JOIN(SELECT
                                                                  t2.FWINECODE AS MaterialId

                                                                FROM

                                                                    QUDE_BiddingPurchaseOrder t1

                                                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t1.FID = t2.FID and t1.FDOCUMENTSTATUS = 'C'

                                                                    INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                                                    INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE

                                                                WHERE
                                                                    FTRANSACTIONS = 1 AND (REPLACE(t7.FPHONE, '-', '') ='{3}' or  REPLACE(t7.FPHONE, '+', '') ='{3}')

                                                                GROUP BY

                                                                    FWINECODE)TS on TS.MaterialId = T4.FMATERIALID
                    LEFT JOIN(SELECT
                                                                  t2.FWINECODE AS MaterialId

                                                                FROM

                                                                    QUDE_Bidding_SalesOrder t1

                                                                    INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID and t1.FDOCUMENTSTATUS = 'C'

                                                                    INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                                                    INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE

                                                                WHERE
                                                                    FTRANSACTIONS = 1 AND (REPLACE(t7.FPHONE, '-', '') ='{3}' or  REPLACE(t7.FPHONE, '+', '') ='{3}')

                                                                GROUP BY

                                                                    FWINECODE)Td on Td.MaterialId = T4.FMATERIALID ORDER BY FIDENTITYID", strTempTable, ((iPageNum - 1) * iPageSize) + 1, iPageNum * iPageSize, Mobile);

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    JObject Data = new JObject();
                    Data.Add("Datas", JArray.FromObject(TotalDatas));
                    string sql = string.Format("select  FIDENTITYID as TotalCount from {0}", strTempTable);
                    var TotalData = DBUtils.ExecuteDynamicObject(ctx, sql);
                    Data.Add("TotalCount", TotalData.Count);

                    result["Result"] = true;
                    result["Message"] = "实时竞价查询成功";
                    result["Data"] = Data;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "实时竞价查询成功，返回查询结果为空！";
                }
                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("实时竞价查询成功查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 竞价采购订单列表
        internal string QueryPurchaseOrder(Context ctx, string Mobile, string OrgNumber, string MaterialName, string TransStatus, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, PurQty,PurAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol,IsFaBu, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FMODIFYDATE DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@"/*dialect*/(SELECT Distinct
                                    t1.FBILLNO AS PurchaseOrderNo,
                                    t1.FTRANSACTIONCODE as TransNo,
                                    CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                    case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                    t9.FNUMBER as MerchantNumber,
                                    t3.FNAME as Merchant,
                                    t4.FNUMBER AS Material,
                                    t2.FPURCHASESOLD AS PurQty,
                                    t2.FPURCHASEPRICE AS PurAmount,
                                    CONVERT(varchar(100), t1.FMODIFYDATE, 120) AS FMODIFYDATE,
                                    case when t1.FTRANSACTIONS = 1 then '采购中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                    case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已入库' end  as LogisticsStatus,
                                    case when t1.FCOLLECTIONIN = 1 then '待付款' when t1.FCOLLECTIONIN = 2 then '已付款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
									t14.FNAME  AS Currency,
									t12.FSYSMBOL AS SysMbol,
                                    CASE WHEN  TS.MaterialId IS NULL THEN 0 ELSE 1 END AS IsFaBu
                                    FROM
									(
		                                                        SELECT
			                                                        t2.FWINECODE AS MaterialId,
			                                                        MAX ( t2.FPURCHASEPRICE ) AS BidPrice
																	
		                                                        FROM
			                                                        QUDE_BiddingPurchaseOrder t1
			                                                        INNER JOIN QUDE_PurchaseOrderEntry t2 ON t1.FID = t2.FID and t1.FDOCUMENTSTATUS = 'C'
			                                                        INNER JOIN T_BD_MATERIAL t3 ON t2.FWINECODE = t3.FMATERIALID
			                                                        INNER JOIN T_BD_MATERIAL_L t4 ON t3.FMATERIALID = t4.FMATERIALID 
                                                                    INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                                                    INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE                                        
		                                                        WHERE
			                                                        FTRANSACTIONS = 1 AND t4.FLOCALEID = @FLocaleId
		                                                        GROUP BY
			                                                        FWINECODE
		                                                        ) t
                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t.MaterialId = t2.FWINECODE 
		                                                        AND t.BidPrice = t2.FPURCHASEPRICE
		                            INNER JOIN QUDE_BiddingPurchaseOrder t1 ON t1.FID = t2.FID 
                                    INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                    INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                    INNER JOIN T_BD_MATERIAL_L MAL ON MAL.FMATERIALID = T4.FMATERIALID  and MAL.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                    INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
									INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
									INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
	                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
									INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = 2052
                                    ");
                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(string.Format(@" INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                        INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE
                                        LEFT JOIN (SELECT
			                                                      t2.FWINECODE AS MaterialId
																	
		                                                        FROM
			                                                        QUDE_BiddingPurchaseOrder t1
			                                                        INNER JOIN QUDE_PurchaseOrderEntry t2 ON t1.FID = t2.FID and t1.FDOCUMENTSTATUS = 'C'
																	INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                                                    INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE 
		                                                        WHERE
			                                                        FTRANSACTIONS = 1 AND (REPLACE(t7.FPHONE, '-', '') ='{0}' or  REPLACE(t7.FPHONE, '+', '') ='{0}')
		                                                        GROUP BY
			                                                        FWINECODE)TS on ts.MaterialId = T4.FMATERIALID", Mobile));
                }
                sbSql.AppendLine(@"  WHERE t1.FDOCUMENTSTATUS = 'C'");
                //if (!string.IsNullOrWhiteSpace(Mobile))
                //{
                //    sbSql.AppendLine(" AND  t7.FPHONE = @Mobile ");
                //    lstParam.Add(new SqlParam("@Mobile", KDDbType.String, Mobile));
                //}
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND t8.FNUMBER =  @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                MaterialName = "%" + MaterialName.Replace("-", " ") + "%";
                if (!string.IsNullOrWhiteSpace(MaterialName))
                {
                    sbSql.AppendLine(" AND REPLACE(MAL.FNAME, '-', ' ') LIKE  @MaterialName ");
                    lstParam.Add(new SqlParam("@MaterialName", KDDbType.String, MaterialName));
                }
                if (!string.IsNullOrWhiteSpace(TransStatus))
                {
                    sbSql.AppendLine(" AND t1.FTRANSACTIONS =  @TransStatus ");
                    lstParam.Add(new SqlParam("@TransStatus", KDDbType.String, TransStatus));
                }
                sbSql.AppendLine(" ) t ");//WHERE TI.FBASEQTY > 0

                sbSql.AppendFormat("/*dialect*/SELECT FIDENTITYID,  PurchaseOrderNo, TransNo, ApplicationDate, Submitdate,MerchantNumber, Merchant, Material, PurQty,PurAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol,IsFaBu  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "竞价采购数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "竞价采购数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价采购数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价采购数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 竞价销售订单列表
        internal string QuerySalesOrder(Context ctx, string Mobile, string OrgNumber, string MaterialName, string TransStatus, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, SalQty,SalAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol,IsFaBu, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FMODIFYDATE DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@"/*dialect*/(SELECT Distinct
                                                t1.FBILLNO AS PurchaseOrderNo,
                                                t1.FTRANSACTIONCODE as TransNo,
                                                CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                                case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                                  CONVERT(varchar(100), t1.FMODIFYDATE, 120) AS FMODIFYDATE,
                                                t9.FNUMBER as MerchantNumber,
                                                t3.FNAME as Merchant,
                                                t4.FNUMBER AS Material,
                                                t2.FBOTTLESSOLD AS SalQty,
                                                t2.FSELLINGPRICE AS SalAmount,
                                                case when t1.FTRANSACTIONS = 1 then '销售中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                                case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已出库' end  as LogisticsStatus,
                                                case when t1.FCOLLECTIONIN = 1 then '待收款' when t1.FCOLLECTIONIN = 2 then '已收款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
                                                t14.FNAME  AS Currency,
                                                t12.FSYSMBOL AS SysMbol,
                                                CASE WHEN  TS.MaterialId IS NULL THEN 0 ELSE 1 END AS IsFaBu
                                                FROM
                                                (
                                                SELECT
                                                t2.FWINECODE AS MaterialId,
                                                MIN ( t2.FSELLINGPRICE ) AS OfferPrice
                                                FROM
                                                QUDE_Bidding_SalesOrder t1
                                                INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID and t1.FDOCUMENTSTATUS = 'C'
                                                INNER JOIN T_BD_MATERIAL t3 ON t2.FWINECODE = t3.FMATERIALID
                                                INNER JOIN T_BD_MATERIAL_L t4 ON t3.FMATERIALID = t4.FMATERIALID
                                                INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                                INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE 
                                                WHERE
                                                FTRANSACTIONS = 1 AND t4.FLOCALEID = 2052
                                                GROUP BY
                                                FWINECODE
                                                ) t
                                                LEFT JOIN QUDE_Sale_OrderEntry t2 ON t.MaterialId = t2.FWINECODE 
                                                AND t.OfferPrice = t2.FSELLINGPRICE
                                                INNER JOIN QUDE_Bidding_SalesOrder t1 ON t1.FID = t2.FID 
                                                INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                                INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                                INNER JOIN T_BD_MATERIAL_L MAL ON MAL.FMATERIALID = T4.FMATERIALID  and MAL.FLocaleID = @FLocaleId
                                                INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = 2052
                                                INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                                INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
                                                INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                                INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = 2052
                                    ");
                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(string.Format(@" INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                        INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE	
                                        LEFT JOIN (SELECT
			                                                      t2.FWINECODE AS MaterialId
																	
		                                                        FROM
			                                                        QUDE_Bidding_SalesOrder t1
			                                                        INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID and t1.FDOCUMENTSTATUS = 'C'
																	INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                                                    INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE
		                                                        WHERE
			                                                        FTRANSACTIONS = 1 AND (REPLACE(t7.FPHONE, '-', '') ='{0}' or  REPLACE(t7.FPHONE, '+', '') ='{0}')
		                                                        GROUP BY
			                                                        FWINECODE)TS on ts.MaterialId = T4.FMATERIALID", Mobile));
                }
                sbSql.AppendLine(@"  WHERE t1.FDOCUMENTSTATUS = 'C'");
                //if (!string.IsNullOrWhiteSpace(Mobile))
                //{
                //    sbSql.AppendLine(" AND  t7.FPHONE = @Mobile ");
                //    lstParam.Add(new SqlParam("@Mobile", KDDbType.String, Mobile));
                //}
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND t8.FNUMBER =  @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                MaterialName = "%" + MaterialName.Replace("-", " ") + "%";
                if (!string.IsNullOrWhiteSpace(MaterialName))
                {
                    sbSql.AppendLine(" AND REPLACE(MAL.FNAME, '-', ' ') LIKE  @MaterialName ");
                    lstParam.Add(new SqlParam("@MaterialName", KDDbType.String, MaterialName));
                }
                if (!string.IsNullOrWhiteSpace(TransStatus))
                {
                    sbSql.AppendLine(" AND t1.FTRANSACTIONS =  @TransStatus ");
                    lstParam.Add(new SqlParam("@TransStatus", KDDbType.String, TransStatus));
                }
                sbSql.AppendLine(" ) t ");//WHERE TI.FBASEQTY > 0

                sbSql.AppendFormat("/*dialect*/SELECT FIDENTITYID,  PurchaseOrderNo, TransNo, ApplicationDate, Submitdate,MerchantNumber, Merchant, Material, SalQty,SalAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol,IsFaBu  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "竞价销售数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "竞价销售数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价销售数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价销售数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 竞价采购订单详情
        internal string QueryPurchaseOrderDetail(Context ctx, string Mobile, string OrgNumber, string Material, string TransStatus, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, PurQty,PurAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY PurAmount DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@"/*dialect*/(select PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant,MATERIAL.FNUMBER AS Material, PurQty,PurAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol from T_BD_MATERIAL MATERIAL left join (SELECT Distinct
                                    t1.FBILLNO AS PurchaseOrderNo,
                                    t1.FTRANSACTIONCODE as TransNo,
                                    CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                    case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                    t9.FNUMBER as MerchantNumber,
                                    t3.FNAME as Merchant,
                                    t4.FNUMBER AS Material,
                                    t2.FPURCHASESOLD AS PurQty,
                                    t2.FPURCHASEPRICE AS PurAmount,
                                    case when t1.FTRANSACTIONS = 1 then '采购中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                    case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已入库' end  as LogisticsStatus,
                                    case when t1.FCOLLECTIONIN = 1 then '待付款' when t1.FCOLLECTIONIN = 2 then '已付款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
									t14.FNAME  AS Currency,
									t12.FSYSMBOL AS SysMbol
									FROM QUDE_BiddingPurchaseOrder t1
                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t2.FID = t1.FID
                                    INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                    INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                    INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                    INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
									INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
									INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
	                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
									INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                    ");
                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(@" 
                                        INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE ");
                }
                sbSql.AppendLine(@"  WHERE t1.FDOCUMENTSTATUS = 'C'");

                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(" AND  (REPLACE(t7.FPHONE, '-', '') = @Mobile or  REPLACE(t7.FPHONE, '+', '') = @Mobile )");
                    lstParam.Add(new SqlParam("@Mobile", KDDbType.String, Mobile));
                }
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND t8.FNUMBER =  @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                if (!string.IsNullOrWhiteSpace(TransStatus))
                {
                    sbSql.AppendLine(" AND t1.FTRANSACTIONS =  @TransStatus ");
                    lstParam.Add(new SqlParam("@TransStatus", KDDbType.String, TransStatus));
                }
                sbSql.AppendLine(" )MATERIALL ON MATERIALL.Material = MATERIAL.FNUMBER ");//WHERE TI.FBASEQTY > 0

                if (!string.IsNullOrWhiteSpace(Material))
                {
                    sbSql.AppendLine(" where  MATERIAL.FNUMBER = @Material ");
                    lstParam.Add(new SqlParam("@Material", KDDbType.String, Material));
                }
                sbSql.AppendLine(" )t ");//WHERE TI.FBASEQTY > 0
                sbSql.AppendFormat("/*dialect*/SELECT FIDENTITYID,  PurchaseOrderNo, TransNo, ApplicationDate, Submitdate,MerchantNumber, Merchant, Material, PurQty,PurAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "竞价采购数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "竞价采购数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价采购数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价采购数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 竞价销售订单详情
        internal string QuerySalesOrderDetail(Context ctx, string Mobile, string OrgNumber, string Material, string TransStatus, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, SalQty,SalAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY SalAmount asc) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@"/*dialect*/(select PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, MATERIAL.FNUMBER AS Material, SalQty,SalAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol from T_BD_MATERIAL MATERIAL left join(SELECT Distinct
                                                t1.FBILLNO AS PurchaseOrderNo,
                                                t1.FTRANSACTIONCODE as TransNo,
                                                CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                                case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                                t9.FNUMBER as MerchantNumber,
                                                t3.FNAME as Merchant,
                                                t4.FNUMBER AS Material,
                                                t2.FBOTTLESSOLD  AS SalQty,
                                                t2.FSELLINGPRICE AS SalAmount,
                                                case when t1.FTRANSACTIONS = 1 then '销售中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                                case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已出库' end  as LogisticsStatus,
                                                case when t1.FCOLLECTIONIN = 1 then '待收款' when t1.FCOLLECTIONIN = 2 then '已收款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
                                                t14.FNAME  AS Currency,
                                                t12.FSYSMBOL AS SysMbol
                                                FROM QUDE_Bidding_SalesOrder t1
                                                INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID 
                                                INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                                INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                                INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = @FLocaleId
                                                INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                                INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
                                                INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                                INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = @FLocaleId
                                                INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                    ");
                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(@" 
                                        INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE	");
                }
                sbSql.AppendLine(@"  WHERE t1.FDOCUMENTSTATUS = 'C'");

                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(" AND  (REPLACE(t7.FPHONE, '-', '') = @Mobile or  REPLACE(t7.FPHONE, '+', '') = @Mobile) ");
                    lstParam.Add(new SqlParam("@Mobile", KDDbType.String, Mobile));
                }
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND t8.FNUMBER =  @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                if (!string.IsNullOrWhiteSpace(TransStatus))
                {
                    sbSql.AppendLine(" AND t1.FTRANSACTIONS =  @TransStatus ");
                    lstParam.Add(new SqlParam("@TransStatus", KDDbType.String, TransStatus));
                }
                sbSql.AppendLine(" )MATERIALL ON MATERIALL.Material = MATERIAL.FNUMBER ");
                if (!string.IsNullOrWhiteSpace(Material))
                {
                    sbSql.AppendLine("where  MATERIAL.FNUMBER = @Material ");
                    lstParam.Add(new SqlParam("@Material", KDDbType.String, Material));
                }
                sbSql.AppendLine(" ) t ");//WHERE TI.FBASEQTY > 0
                sbSql.AppendFormat("/*dialect*/SELECT FIDENTITYID,  PurchaseOrderNo, TransNo, ApplicationDate, Submitdate,MerchantNumber, Merchant, Material, SalQty,SalAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SysMbol  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "竞价销售数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "竞价销售数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价销售数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价销售数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 我的竞价采购订单列表
        internal string QueryPurchaseOrderDetails(Context ctx, string Mobile, string OrgNumber, string Material, string TransStatus, string TransNo, string GbApplicationDate, string LbApplicationDate, string GbSubmitdate, string LbSubmitdate, string MaterialName, string GbPurQty, string LbPurQty, string GbPurAmount, string LbPurAmount, string LogisticsStatus, string CollectStatus, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);
                if (TransStatus == "2")
                {
                    sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, PurQty,PurAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SellingPrice,BottlesSold,FBaseQty,SysMbol, ");
                    sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FLOGISTICSSTATUS,FCOLLECTIONIN ASC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                    sbSql.AppendLine(@"/*dialect*/(SELECT Distinct
                                    t1.FBILLNO AS PurchaseOrderNo,
                                    t1.FTRANSACTIONCODE as TransNo,
                                    CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                    case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                    t9.FNUMBER as MerchantNumber,
                                    t3.FNAME as Merchant,
                                    t4.FNUMBER AS Material,
                                    t2.FPURCHASESOLD  AS PurQty,
                                    t2.FPURCHASEPRICE AS PurAmount,
                                    t1.FLOGISTICSSTATUS as FLOGISTICSSTATUS,
                                    t1.FCOLLECTIONIN AS FCOLLECTIONIN,
                                    case when t1.FTRANSACTIONS = 1 then '采购中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                    case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已入库' end  as LogisticsStatus,
                                    case when t1.FCOLLECTIONIN = 1 then '待付款' when t1.FCOLLECTIONIN = 2 then '已付款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
									t14.FNAME  AS Currency,
                                    isnull(ts.FSELLINGPRICE,0) as SellingPrice,
                                    isnull(ts.FBOTTLESSOLD,0) as BottlesSold,
									isnull(kc.FBaseQty,0) as FBaseQty,
									t12.FSYSMBOL AS SysMbol
									FROM QUDE_BiddingPurchaseOrder t1
                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t2.FID = t1.FID 
                                    INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                    INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                    INNER JOIN T_BD_MATERIAL_L t15 on t15.FMATERIALID = T4.FMATERIALID and t15.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                    INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
									INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
									INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
	                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
									INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                    left join (select  t1.FWINECODE as FWINECODE,t.FAPPLICATIONORGID as FAPPLICATIONORGID,min(t1.FSELLINGPRICE) as FSELLINGPRICE,max(t1.FBOTTLESSOLD) as FBOTTLESSOLD
                                        from  QUDE_Bidding_SalesOrder t 
                                        inner join QUDE_Sale_OrderEntry t1 on t1.FID = t.FID and t.FTRANSACTIONS = 1 and t.FDOCUMENTSTATUS = 'C'
                                        group by t1.FWINECODE,t.FAPPLICATIONORGID
										)ts on ts.FWINECODE = t4.FMATERIALID and ts.FAPPLICATIONORGID = t1.FAPPLICATIONORGID
								    left join (select sum(t.FBaseQty - isnull(t2.FBASEQTY,0))  as FBaseQty,t.FMATERIALID as FMATERIALID,FOWNERID as FOWNERID  
									from T_STK_INVENTORY  t
                                                inner join T_BD_STOCK t1 on t1.FSTOCKID = t.FSTOCKID
                                                left join 
                                                (select sum (FBASEQTY) as FBASEQTY,FSUPPLYINTERID from T_PLN_RESERVELINKENTRY 
                                                group by FSUPPLYINTERID
                                                )t2 on t2.FSUPPLYINTERID = t.FID 
                                                where  FOWNERTYPEID = 'BD_Customer' and  t.FBASEQTY <> 0
												group by t.FMATERIALID,FOWNERID)kc on kc.FMATERIALID = t4.FMATERIALID and kc.FOWNERID = t9.FCUSTOMERID 
                                    ");
                }
                else
                {
                    sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, PurQty,PurAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SellingPrice,BottlesSold,FBaseQty,SysMbol, ");
                    sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FMODIFYDATE DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                    sbSql.AppendLine(@"/*dialect*/(SELECT Distinct
                                    t1.FBILLNO AS PurchaseOrderNo,
                                    t1.FTRANSACTIONCODE as TransNo,
                                    CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                    t1.FMODIFYDATE  as FMODIFYDATE,
                                    case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                    t9.FNUMBER as MerchantNumber,
                                    t3.FNAME as Merchant,
                                    t4.FNUMBER AS Material,
                                    t2.FPURCHASESOLD  AS PurQty,
                                    t2.FPURCHASEPRICE AS PurAmount,
                                    t1.FLOGISTICSSTATUS as FLOGISTICSSTATUS,
                                    t1.FCOLLECTIONIN AS FCOLLECTIONIN,
                                    case when t1.FTRANSACTIONS = 1 then '采购中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                    case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已入库' end  as LogisticsStatus,
                                    case when t1.FCOLLECTIONIN = 1 then '待付款' when t1.FCOLLECTIONIN = 2 then '已付款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
									t14.FNAME  AS Currency,
                                    isnull(ts.FSELLINGPRICE,0) as SellingPrice,
                                    isnull(ts.FBOTTLESSOLD,0) as BottlesSold,
									isnull(kc.FBaseQty,0) as FBaseQty,
									t12.FSYSMBOL AS SysMbol
									FROM QUDE_BiddingPurchaseOrder t1
                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t2.FID = t1.FID 
                                    INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                    INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                    INNER JOIN T_BD_MATERIAL_L t15 on t15.FMATERIALID = T4.FMATERIALID and t15.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                    INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
									INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
									INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
	                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID
									INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = @FLocaleId
                                    INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                    left join (select  t1.FWINECODE as FWINECODE,t.FAPPLICATIONORGID as FAPPLICATIONORGID,min(t1.FSELLINGPRICE) as FSELLINGPRICE,max(t1.FBOTTLESSOLD) as FBOTTLESSOLD
                                        from  QUDE_Bidding_SalesOrder t 
                                        inner join QUDE_Sale_OrderEntry t1 on t1.FID = t.FID and t.FTRANSACTIONS = 1 and t.FDOCUMENTSTATUS = 'C'
                                        group by t1.FWINECODE,t.FAPPLICATIONORGID
										)ts on ts.FWINECODE = t4.FMATERIALID and ts.FAPPLICATIONORGID = t1.FAPPLICATIONORGID
								    left join (select sum(t.FBaseQty - isnull(t2.FBASEQTY,0))  as FBaseQty,t.FMATERIALID as FMATERIALID,FOWNERID as FOWNERID  
									from T_STK_INVENTORY  t
                                                inner join T_BD_STOCK t1 on t1.FSTOCKID = t.FSTOCKID
                                                left join 
                                                (select sum (FBASEQTY) as FBASEQTY,FSUPPLYINTERID from T_PLN_RESERVELINKENTRY 
                                                group by FSUPPLYINTERID
                                                )t2 on t2.FSUPPLYINTERID = t.FID 
                                                where  FOWNERTYPEID = 'BD_Customer' and  t.FBASEQTY <> 0
												group by t.FMATERIALID,FOWNERID)kc on kc.FMATERIALID = t4.FMATERIALID and kc.FOWNERID = t9.FCUSTOMERID 
                                    ");
                }


                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(@" 
                                        INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE ");
                }
                sbSql.AppendLine(@"  WHERE t1.FDOCUMENTSTATUS = 'C'");
                if (!string.IsNullOrWhiteSpace(Material))
                {
                    sbSql.AppendLine(" AND  T4.FNUMBER = @Material ");
                    lstParam.Add(new SqlParam("@Material", KDDbType.String, Material));
                }
                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(" AND ( REPLACE(t7.FPHONE, '-', '') = @Mobile or  REPLACE(t7.FPHONE, '+', '') = @Mobile) ");
                    lstParam.Add(new SqlParam("@Mobile", KDDbType.String, Mobile));
                }
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND t8.FNUMBER =  @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                if (!string.IsNullOrWhiteSpace(TransStatus))
                {
                    sbSql.AppendLine(" AND t1.FTRANSACTIONS =  @TransStatus ");
                    lstParam.Add(new SqlParam("@TransStatus", KDDbType.String, TransStatus));
                }

                if (TransStatus == "1")
                {
                    if (!string.IsNullOrWhiteSpace(TransNo))
                    {
                        sbSql.AppendLine(" AND t1.FBILLNO =  @TransNo ");
                        lstParam.Add(new SqlParam("@TransNo", KDDbType.String, TransNo));
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(TransNo))
                    {
                        sbSql.AppendLine(" AND t1.FTRANSACTIONCODE =  @TransNo ");
                        lstParam.Add(new SqlParam("@TransNo", KDDbType.String, TransNo));
                    }
                }



                if (!string.IsNullOrWhiteSpace(GbApplicationDate))
                {
                    sbSql.AppendLine(" AND CONVERT(varchar(100), t1.FAPPLICATIONDATE, 23) >=  @GbApplicationDate ");
                    lstParam.Add(new SqlParam("@GbApplicationDate", KDDbType.String, GbApplicationDate));
                }


                if (!string.IsNullOrWhiteSpace(LbApplicationDate))
                {
                    sbSql.AppendLine(" AND CONVERT(varchar(100), t1.FAPPLICATIONDATE, 23) <=  @LbApplicationDate ");
                    lstParam.Add(new SqlParam("@LbApplicationDate", KDDbType.String, LbApplicationDate));
                }


                if (!string.IsNullOrWhiteSpace(GbSubmitdate))
                {
                    sbSql.AppendLine(" AND CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 23) >=  @GbSubmitdate ");
                    lstParam.Add(new SqlParam("@GbSubmitdate", KDDbType.String, GbSubmitdate));
                }

                if (!string.IsNullOrWhiteSpace(LbSubmitdate))
                {
                    sbSql.AppendLine(" AND CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 23) <= @LbSubmitdate ");
                    lstParam.Add(new SqlParam("@LbSubmitdate", KDDbType.String, LbSubmitdate));
                }
                MaterialName = "%" + MaterialName.Replace("-", " ") + "%";
                if (!string.IsNullOrWhiteSpace(MaterialName))
                {
                    sbSql.AppendLine(" AND REPLACE(t15.FNAME, '-', ' ') LIKE  @MaterialName ");
                    lstParam.Add(new SqlParam("@MaterialName", KDDbType.String, MaterialName));
                }

                if (!string.IsNullOrWhiteSpace(GbPurQty))
                {
                    sbSql.AppendLine("AND t2.FPURCHASESOLD >=  @GbPurQty ");
                    lstParam.Add(new SqlParam("@GbPurQty", KDDbType.String, GbPurQty));
                }

                if (!string.IsNullOrWhiteSpace(LbPurQty))
                {
                    sbSql.AppendLine(" AND t2.FPURCHASESOLD <=  @LbPurQty ");
                    lstParam.Add(new SqlParam("@LbPurQty", KDDbType.String, LbPurQty));
                }


                if (!string.IsNullOrWhiteSpace(GbPurAmount))
                {
                    sbSql.AppendLine(" AND t2.FPURCHASEPRICE >=  @GbPurAmount ");
                    lstParam.Add(new SqlParam("@GbPurAmount", KDDbType.String, GbPurAmount));
                }

                if (!string.IsNullOrWhiteSpace(LbPurAmount))
                {
                    sbSql.AppendLine(" AND t2.FPURCHASEPRICE <=  @LbPurAmount ");
                    lstParam.Add(new SqlParam("@LbPurAmount", KDDbType.String, LbPurAmount));
                }

                if (!string.IsNullOrWhiteSpace(LogisticsStatus))
                {
                    sbSql.AppendLine(" AND t1.FLOGISTICSSTATUS =  @LogisticsStatus ");
                    lstParam.Add(new SqlParam("@LogisticsStatus", KDDbType.String, LogisticsStatus));
                }

                if (!string.IsNullOrWhiteSpace(CollectStatus))
                {
                    sbSql.AppendLine(" AND t1.FCOLLECTIONIN =  @CollectStatus ");
                    lstParam.Add(new SqlParam("@CollectStatus", KDDbType.String, CollectStatus));
                }
                sbSql.AppendLine(" ) t ");//WHERE TI.FBASEQTY > 0

                sbSql.AppendFormat("/*dialect*/SELECT FIDENTITYID,  PurchaseOrderNo, TransNo, ApplicationDate, Submitdate,MerchantNumber, Merchant, Material, PurQty,PurAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,SellingPrice,BottlesSold,FBaseQty,SysMbol  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "竞价采购数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "竞价采购数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价采购数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价采购数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 我的竞价销售订单列表
        internal string QuerySalesOrderDetails(Context ctx, string Mobile, string OrgNumber, string Material, string TransStatus, string TransNo, string GbApplicationDate, string LbApplicationDate, string GbSubmitdate, string LbSubmitdate, string MaterialName, string GbSalQty, string LbSalQty, string GbSalAmount, string LbSalAmount, string LogisticsStatus, string CollectStatus, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                if (TransStatus == "2")
                {
                    sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, SalQty,SalAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,PurChasePrice,PurChaseSold,FBaseQty,SysMbol, ");
                    sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FLOGISTICSSTATUS,FCOLLECTIONIN ASC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                    sbSql.AppendLine(@"/*dialect*/(SELECT Distinct
                                                t1.FBILLNO AS PurchaseOrderNo,
                                                t1.FTRANSACTIONCODE as TransNo,
                                                CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                                case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                                t9.FNUMBER as MerchantNumber,
                                                t3.FNAME as Merchant,
                                                t4.FNUMBER AS Material,
                                                t2.FBOTTLESSOLD AS SalQty,
                                                t2.FSELLINGPRICE AS SalAmount,
                                                t1.FLOGISTICSSTATUS as FLOGISTICSSTATUS,
                                                t1.FCOLLECTIONIN AS FCOLLECTIONIN,
                                                case when t1.FTRANSACTIONS = 1 then '销售中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                                case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已出库' end  as LogisticsStatus,
                                                case when t1.FCOLLECTIONIN = 1 then '待收款' when t1.FCOLLECTIONIN = 2 then '已收款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
                                                t14.FNAME  AS Currency,
                                                isnull(ts.FPURCHASEPRICE,0) as PurChasePrice,
                                                isnull(ts.FPURCHASESOLD,0) as PurChaseSold,
									            isnull(kc.FBaseQty,0) as FBaseQty,
                                                t12.FSYSMBOL AS SysMbol
                                                FROM QUDE_Bidding_SalesOrder t1
                                                INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID 
                                                INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                                INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                                INNER JOIN T_BD_MATERIAL_L t15 on t15.FMATERIALID = T4.FMATERIALID and t15.FLocaleID = @FLocaleId
                                                INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = @FLocaleId
                                                INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                                INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
                                                INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                                INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = @FLocaleId
                                                INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                         left join (select  t1.FWINECODE as FWINECODE,t.FAPPLICATIONORGID as FAPPLICATIONORGID,max(t1.FPURCHASEPRICE) as FPURCHASEPRICE,max(t1.FPURCHASESOLD) as FPURCHASESOLD
                                        from  QUDE_BiddingPurchaseOrder t 
                                        inner join QUDE_PurchaseOrderEntry t1 on t1.FID = t.FID and t.FTRANSACTIONS = 1 and t.FDOCUMENTSTATUS = 'C'
                                        group by t1.FWINECODE,t.FAPPLICATIONORGID
										)ts on ts.FWINECODE = t4.FMATERIALID and ts.FAPPLICATIONORGID = t1.FAPPLICATIONORGID
								    left join (select sum(t.FBaseQty - isnull(t2.FBASEQTY,0))  as FBaseQty,t.FMATERIALID as FMATERIALID,FOWNERID as FOWNERID  
									from T_STK_INVENTORY  t
                                                inner join T_BD_STOCK t1 on t1.FSTOCKID = t.FSTOCKID
                                                left join 
                                                (select sum (FBASEQTY) as FBASEQTY,FSUPPLYINTERID from T_PLN_RESERVELINKENTRY 
                                                group by FSUPPLYINTERID
                                                )t2 on t2.FSUPPLYINTERID = t.FID 
                                                where  FOWNERTYPEID = 'BD_Customer' and  t.FBASEQTY <> 0
												group by t.FMATERIALID,FOWNERID)kc on kc.FMATERIALID = t4.FMATERIALID and kc.FOWNERID = t9.FCUSTOMERID
                                    ");
                }
                else
                {
                    sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, SalQty,SalAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,PurChasePrice,PurChaseSold,FBaseQty,SysMbol, ");
                    sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FMODIFYDATE DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                    sbSql.AppendLine(@"/*dialect*/(SELECT Distinct
                                                t1.FBILLNO AS PurchaseOrderNo,
                                                t1.FTRANSACTIONCODE as TransNo,
                                                CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                                t1.FMODIFYDATE  as FMODIFYDATE,
                                                case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                                t9.FNUMBER as MerchantNumber,
                                                t3.FNAME as Merchant,
                                                t4.FNUMBER AS Material,
                                                t2.FBOTTLESSOLD AS SalQty,
                                                t2.FSELLINGPRICE AS SalAmount,
                                                t1.FLOGISTICSSTATUS as FLOGISTICSSTATUS,
                                                t1.FCOLLECTIONIN AS FCOLLECTIONIN,
                                                case when t1.FTRANSACTIONS = 1 then '销售中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                                case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已出库' end  as LogisticsStatus,
                                                case when t1.FCOLLECTIONIN = 1 then '待收款' when t1.FCOLLECTIONIN = 2 then '已收款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
                                                t14.FNAME  AS Currency,
                                                isnull(ts.FPURCHASEPRICE,0) as PurChasePrice,
                                                isnull(ts.FPURCHASESOLD,0) as PurChaseSold,
									            isnull(kc.FBaseQty,0) as FBaseQty,
                                                t12.FSYSMBOL AS SysMbol
                                                FROM QUDE_Bidding_SalesOrder t1
                                                INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID 
                                                INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                                INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                                INNER JOIN T_BD_MATERIAL_L t15 on t15.FMATERIALID = T4.FMATERIALID and t15.FLocaleID = @FLocaleId
                                                INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = @FLocaleId
                                                INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                                INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
                                                INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                                INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = @FLocaleId
                                                INNER JOIN QUDE_StoreEntity t6 ON t6.FID = t1.F_QUDE_MERCHANT
                                        left join (select  t1.FWINECODE as FWINECODE,t.FAPPLICATIONORGID as FAPPLICATIONORGID,max(t1.FPURCHASEPRICE) as FPURCHASEPRICE,max(t1.FPURCHASESOLD) as FPURCHASESOLD
                                        from  QUDE_BiddingPurchaseOrder t 
                                        inner join QUDE_PurchaseOrderEntry t1 on t1.FID = t.FID and t.FTRANSACTIONS = 1 and t.FDOCUMENTSTATUS = 'C'
                                        group by t1.FWINECODE,t.FAPPLICATIONORGID
										)ts on ts.FWINECODE = t4.FMATERIALID and ts.FAPPLICATIONORGID = t1.FAPPLICATIONORGID
								    left join (select sum(t.FBaseQty - isnull(t2.FBASEQTY,0))  as FBaseQty,t.FMATERIALID as FMATERIALID,FOWNERID as FOWNERID  
									from T_STK_INVENTORY  t
                                                inner join T_BD_STOCK t1 on t1.FSTOCKID = t.FSTOCKID
                                                left join 
                                                (select sum (FBASEQTY) as FBASEQTY,FSUPPLYINTERID from T_PLN_RESERVELINKENTRY 
                                                group by FSUPPLYINTERID
                                                )t2 on t2.FSUPPLYINTERID = t.FID 
                                                where  FOWNERTYPEID = 'BD_Customer' and  t.FBASEQTY <> 0
												group by t.FMATERIALID,FOWNERID)kc on kc.FMATERIALID = t4.FMATERIALID and kc.FOWNERID = t9.FCUSTOMERID
                                    ");
                }

                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(@" 
                                        INNER JOIN T_SEC_user t7 on t7.FUSERID = t6.F_QUDE_STOREFILE	");
                }
                sbSql.AppendLine(@"  WHERE t1.FDOCUMENTSTATUS = 'C'");
                if (!string.IsNullOrWhiteSpace(Material))
                {
                    sbSql.AppendLine(" AND  T4.FNUMBER = @Material ");
                    lstParam.Add(new SqlParam("@Material", KDDbType.String, Material));
                }
                if (!string.IsNullOrWhiteSpace(Mobile))
                {
                    sbSql.AppendLine(" AND ( REPLACE(t7.FPHONE, '-', '') = @Mobile or  REPLACE(t7.FPHONE, '+', '') = @Mobile) ");
                    lstParam.Add(new SqlParam("@Mobile", KDDbType.String, Mobile));
                }
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND t8.FNUMBER =  @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                if (!string.IsNullOrWhiteSpace(TransStatus))
                {
                    sbSql.AppendLine(" AND t1.FTRANSACTIONS =  @TransStatus ");
                    lstParam.Add(new SqlParam("@TransStatus", KDDbType.String, TransStatus));
                }
                if (TransStatus == "1")
                {
                    if (!string.IsNullOrWhiteSpace(TransNo))
                    {
                        sbSql.AppendLine(" AND t1.FBILLNO =  @TransNo ");
                        lstParam.Add(new SqlParam("@TransNo", KDDbType.String, TransNo));
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(TransNo))
                    {
                        sbSql.AppendLine(" AND t1.FTRANSACTIONCODE =  @TransNo ");
                        lstParam.Add(new SqlParam("@TransNo", KDDbType.String, TransNo));
                    }
                }


                if (!string.IsNullOrWhiteSpace(GbApplicationDate))
                {
                    sbSql.AppendLine(" AND CONVERT(varchar(100), t1.FAPPLICATIONDATE, 23) >=  @GbApplicationDate ");
                    lstParam.Add(new SqlParam("@GbApplicationDate", KDDbType.String, GbApplicationDate));
                }


                if (!string.IsNullOrWhiteSpace(LbApplicationDate))
                {
                    sbSql.AppendLine(" AND CONVERT(varchar(100), t1.FAPPLICATIONDATE, 23) <=  @LbApplicationDate ");
                    lstParam.Add(new SqlParam("@LbApplicationDate", KDDbType.String, LbApplicationDate));
                }


                if (!string.IsNullOrWhiteSpace(GbSubmitdate))
                {
                    sbSql.AppendLine(" AND CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 23) >=  @GbSubmitdate ");
                    lstParam.Add(new SqlParam("@GbSubmitdate", KDDbType.String, GbSubmitdate));
                }

                if (!string.IsNullOrWhiteSpace(LbSubmitdate))
                {
                    sbSql.AppendLine(" AND CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 23) <= @LbSubmitdate ");
                    lstParam.Add(new SqlParam("@LbSubmitdate", KDDbType.String, LbSubmitdate));
                }
                MaterialName = "%" + MaterialName.Replace("-", " ") + "%";
                if (!string.IsNullOrWhiteSpace(MaterialName))
                {
                    sbSql.AppendLine(" AND REPLACE(t15.FNAME, '-', ' ') LIKE  @MaterialName ");
                    lstParam.Add(new SqlParam("@MaterialName", KDDbType.String, MaterialName));
                }

                if (!string.IsNullOrWhiteSpace(GbSalQty))
                {
                    sbSql.AppendLine("AND t2.FBOTTLESSOLD >=  @GbSalQty ");
                    lstParam.Add(new SqlParam("@GbSalQty", KDDbType.String, GbSalQty));
                }

                if (!string.IsNullOrWhiteSpace(LbSalQty))
                {
                    sbSql.AppendLine(" AND t2.FBOTTLESSOLD <=  @LbSalQty ");
                    lstParam.Add(new SqlParam("@LbSalQty", KDDbType.String, LbSalQty));
                }


                if (!string.IsNullOrWhiteSpace(GbSalAmount))
                {
                    sbSql.AppendLine(" AND t2.FSELLINGPRICE >=  @GbSalAmount ");
                    lstParam.Add(new SqlParam("@GbSalAmount", KDDbType.String, GbSalAmount));
                }

                if (!string.IsNullOrWhiteSpace(LbSalAmount))
                {
                    sbSql.AppendLine(" AND t2.FSELLINGPRICE <=  @LbSalAmount ");
                    lstParam.Add(new SqlParam("@LbSalAmount", KDDbType.String, LbSalAmount));
                }

                if (!string.IsNullOrWhiteSpace(LogisticsStatus))
                {
                    sbSql.AppendLine(" AND t1.FLOGISTICSSTATUS =  @LogisticsStatus ");
                    lstParam.Add(new SqlParam("@LogisticsStatus", KDDbType.String, LogisticsStatus));
                }

                if (!string.IsNullOrWhiteSpace(CollectStatus))
                {
                    sbSql.AppendLine(" AND t1.FCOLLECTIONIN =  @CollectStatus ");
                    lstParam.Add(new SqlParam("@CollectStatus", KDDbType.String, CollectStatus));
                }


                sbSql.AppendLine(" ) t ");//WHERE TI.FBASEQTY > 0

                sbSql.AppendFormat("/*dialect*/SELECT FIDENTITYID,  PurchaseOrderNo, TransNo, ApplicationDate, Submitdate,MerchantNumber, Merchant, Material, SalQty,SalAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,PurChasePrice,PurChaseSold,FBaseQty,SysMbol  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "竞价销售数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "竞价销售数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价销售数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价销售数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 批量查询我的竞价销售订单列表
        internal string AllQuerySalesOrderDetails(Context ctx, string Mobile, string OrgNumber, string Material, JObject result)
        {
            try
            {
                result["Result"] = false;
                string sql = "";
                if (!string.IsNullOrWhiteSpace(Material))
                {
                    sql = string.Format(@"/*dialect*/select  Distinct
                                                t.FNUMBER AS Material,
                                                isnull(sal.SalechaseOrderNo,'') as SalechaseOrderNo,
                                                isnull(ts.FPURCHASEPRICE,0) as PurChasePrice,
                                                isnull(ts.FPURCHASESOLD,0) as PurChaseSold,
                                                isnull(sal.SalQty,0) AS SalQty,
                                                isnull(sal.SalAmount,0)AS SalAmount,
                                                isnull(sal.FTRANSACTIONS,0) as TransStatus
                                                from T_BD_MATERIAL t
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FUSEORGID
                                                left join (select  t1.FWINECODE as FWINECODE,t.FAPPLICATIONORGID as FAPPLICATIONORGID,max(t1.FPURCHASEPRICE) as FPURCHASEPRICE,max(t1.FPURCHASESOLD) as FPURCHASESOLD
                                                from  QUDE_BiddingPurchaseOrder t 
                                                inner join QUDE_PurchaseOrderEntry t1 on t1.FID = t.FID and t.FTRANSACTIONS = 1 and t.FDOCUMENTSTATUS = 'C'
                                                group by t1.FWINECODE,t.FAPPLICATIONORGID
                                                )ts on ts.FWINECODE = t.FMATERIALID and ts.FAPPLICATIONORGID = t1.FORGID
                                                left join (select t2.FWINECODE as Material,t.FBILLNO as SalechaseOrderNo,FTRANSACTIONS,t2.FBOTTLESSOLD AS SalQty,
                                                t2.FSELLINGPRICE AS SalAmount
                                                from QUDE_Bidding_SalesOrder t
                                                inner join QUDE_Sale_OrderEntry t2 ON t.FID = t2.FID 
                                                inner join QUDE_StoreEntity t3 ON t3.FID = t.F_QUDE_MERCHANT
                                                inner join T_SEC_user t4 on t4.FUSERID = t3.F_QUDE_STOREFILE 
                                                where  (REPLACE(t4.FPHONE, '-', '') ='{1}' or  REPLACE(t4.FPHONE, '+', '') ='{1}') and t.FTRANSACTIONS <> 2 and t.FDOCUMENTSTATUS = 'C'
                                                )sal on sal.Material = t.FMATERIALID
                                                where t1.FNUMBER = '{0}' and t.FDOCUMENTSTATUS = 'C'  and t.FNUMBER in ({2})", OrgNumber, Mobile, Material);
                }
                else
                {
                    sql = string.Format(@"/*dialect*/select  Distinct
                                                t.FNUMBER AS Material,
                                                isnull(sal.SalechaseOrderNo,'') as SalechaseOrderNo,
                                                isnull(ts.FPURCHASEPRICE,0) as PurChasePrice,
                                                isnull(ts.FPURCHASESOLD,0) as PurChaseSold,
                                                isnull(sal.SalQty,0) AS SalQty,
                                                isnull(sal.SalAmount,0)AS SalAmount,
                                                isnull(sal.FTRANSACTIONS,0) as TransStatus
                                                from T_BD_MATERIAL t
                                                inner join T_ORG_ORGANIZATIONS t1 on t1.FORGID = t.FUSEORGID
                                                left join (select  t1.FWINECODE as FWINECODE,t.FAPPLICATIONORGID as FAPPLICATIONORGID,max(t1.FPURCHASEPRICE) as FPURCHASEPRICE,max(t1.FPURCHASESOLD) as FPURCHASESOLD
                                                from  QUDE_BiddingPurchaseOrder t 
                                                inner join QUDE_PurchaseOrderEntry t1 on t1.FID = t.FID and t.FTRANSACTIONS = 1 and t.FDOCUMENTSTATUS = 'C'
                                                group by t1.FWINECODE,t.FAPPLICATIONORGID
                                                )ts on ts.FWINECODE = t.FMATERIALID and ts.FAPPLICATIONORGID = t1.FORGID
                                                inner join (select t2.FWINECODE as Material,t.FBILLNO as SalechaseOrderNo,FTRANSACTIONS,t2.FBOTTLESSOLD AS SalQty,
                                                t2.FSELLINGPRICE AS SalAmount
                                                from QUDE_Bidding_SalesOrder t
                                                inner join QUDE_Sale_OrderEntry t2 ON t.FID = t2.FID
                                                inner join QUDE_StoreEntity t3 ON t3.FID = t.F_QUDE_MERCHANT
                                                inner join T_SEC_user t4 on t4.FUSERID = t3.F_QUDE_STOREFILE 
                                                where (REPLACE(t4.FPHONE, '-', '') ='{1}' or  REPLACE(t4.FPHONE, '+', '') ='{1}') and t.FTRANSACTIONS <> 2 and t.FDOCUMENTSTATUS = 'C'
                                                )sal on sal.Material = t.FMATERIALID
                                                where t1.FNUMBER = '{0}' and t.FDOCUMENTSTATUS = 'C'", OrgNumber, Mobile);
                }

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "竞价销售数据查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价销售数据查询成功，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价销售数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 我的竞价采购订单
        internal string QueryPurchaseOrderRetail(Context ctx, string BillNo, string OrgNumber, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, PurQty,PurAmount,PurchaseCost,Servicerate,AllAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,NewPurAmount,FBaseQty,SysMbol, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY PurAmount DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@"/*dialect*/(SELECT
                                    t1.FBILLNO AS PurchaseOrderNo,
                                    t1.FTRANSACTIONCODE as TransNo,
                                    CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                    case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                    t9.FNUMBER as MerchantNumber,
                                    t3.FNAME as Merchant,
                                    t4.FNUMBER AS Material,
                                    t2.FPURCHASESOLD AS PurQty,
                                    t2.FPURCHASEPRICE AS PurAmount,
                                    FPurchaseCost as PurchaseCost,
									FSERVICERATE as Servicerate,
									FALLAmount as AllAmount,
                                    case when t1.FTRANSACTIONS = 1 then '采购中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                    case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已入库' end  as LogisticsStatus,
                                    case when t1.FCOLLECTIONIN = 1 then '待付款' when t1.FCOLLECTIONIN = 2 then '已付款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
									t14.FNAME  AS Currency,
									isnull(ts.FPURCHASEPRICE,0) as NewPurAmount,
									isnull(kc.FBaseQty,0) as FBaseQty,
									t12.FSYSMBOL AS SysMbol
									FROM QUDE_BiddingPurchaseOrder t1
                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t2.FID = t1.FID 
                                    INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                    INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                    INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = 2052
                                    INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                    INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
									INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
									INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
	                                INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
									INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = 2052
									left join (select  t1.FWINECODE as FWINECODE,t.FAPPLICATIONORGID as FAPPLICATIONORGID,min(t1.FSELLINGPRICE) as FPURCHASEPRICE
                                        from  QUDE_Bidding_SalesOrder t 
                                        inner join QUDE_Sale_OrderEntry t1 on t1.FID = t.FID and t.FTRANSACTIONS = 1 and t.FDOCUMENTSTATUS = 'C'
                                        group by t1.FWINECODE,t.FAPPLICATIONORGID
										)ts on ts.FWINECODE = t4.FMATERIALID and ts.FAPPLICATIONORGID = t1.FAPPLICATIONORGID
								    left join (select sum(t.FBaseQty - isnull(t2.FBASEQTY,0))  as FBaseQty,t.FMATERIALID as FMATERIALID,FOWNERID as FOWNERID  
									from T_STK_INVENTORY  t
                                                inner join T_BD_STOCK t1 on t1.FSTOCKID = t.FSTOCKID
                                                left join 
                                                (select sum (FBASEQTY) as FBASEQTY,FSUPPLYINTERID from T_PLN_RESERVELINKENTRY 
                                                group by FSUPPLYINTERID
                                                )t2 on t2.FSUPPLYINTERID = t.FID 
                                                where  FOWNERTYPEID = 'BD_Customer' and  t.FBASEQTY <> 0
												group by t.FMATERIALID,FOWNERID)kc on kc.FMATERIALID = t4.FMATERIALID and kc.FOWNERID = t9.FCUSTOMERID 
                                    ");
                sbSql.AppendLine(@"  WHERE t1.FDOCUMENTSTATUS = 'C'");
                if (!string.IsNullOrWhiteSpace(BillNo))
                {
                    sbSql.AppendLine(" AND  t1.FBILLNO = @BillNo ");
                    lstParam.Add(new SqlParam("@BillNo", KDDbType.String, BillNo));
                }
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND t8.FNUMBER =  @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }
                sbSql.AppendLine(" ) t ");//WHERE TI.FBASEQTY > 0

                sbSql.AppendFormat("/*dialect*/SELECT FIDENTITYID,  PurchaseOrderNo, TransNo, ApplicationDate, Submitdate,MerchantNumber, Merchant, Material, PurQty,PurAmount,PurchaseCost,Servicerate,AllAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,NewPurAmount,FBaseQty,SysMbol  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "竞价采购数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "竞价采购数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价采购数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价采购数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 我的竞价销售订单详情
        internal string QuerySalesOrderRetail(Context ctx, string BillNo, string OrgNumber, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("/*dialect*/SELECT PurchaseOrderNo, TransNo, ApplicationDate, Submitdate, MerchantNumber,Merchant, Material, SalQty,SalAmount,ActualPrice,Servicerate,AllAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,NewSalAmount,FBaseQty,SysMbol, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY SalAmount asc) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@"/*dialect*/(SELECT
                                                    t1.FBILLNO AS PurchaseOrderNo,
                                                    t1.FTRANSACTIONCODE as TransNo,
                                                    CONVERT(varchar(100), t1.FAPPLICATIONDATE, 120) AS ApplicationDate,
                                                    case when isnull(t1.FSUBMITDATE,'') = '' then '' else CONVERT(varchar(100), isnull(t1.FSUBMITDATE,''), 120) end as Submitdate,
                                                    t9.FNUMBER as MerchantNumber,
                                                    t3.FNAME as Merchant,
                                                    t4.FNUMBER AS Material,
                                                    t2.FBOTTLESSOLD AS SalQty,
                                                    t2.FSELLINGPRICE AS SalAmount,
                                                    FActualPrice as ActualPrice,
			                                        FSERVICERATE as Servicerate,
			                                        FALLAmount as AllAmount,
                                                    case when t1.FTRANSACTIONS = 1 then '销售中' when t1.FTRANSACTIONS = 2 then '已成交' when t1.FTRANSACTIONS = 3 then '已失效' end  as TransStatus,
                                                    case when t1.FLOGISTICSSTATUS = 1 then '运输中' when t1.FLOGISTICSSTATUS = 2 then '已到货' when t1.FLOGISTICSSTATUS = 3 then '已出库' end  as LogisticsStatus,
                                                    case when t1.FCOLLECTIONIN = 1 then '待收款' when t1.FCOLLECTIONIN = 2 then '已收款' when t1.FCOLLECTIONIN = 3 then '过期' end as  CollectStatus,
                                                    t14.FNAME  AS Currency,
			                                        isnull(ts.FSELLINGPRICE,0) as NewSalAmount,
			                                        isnull(kc.FBaseQty,0) as FBaseQty,
                                                    t12.FSYSMBOL AS SysMbol
                                                    FROM QUDE_Bidding_SalesOrder t1
                                                    INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID 
                                                    INNER JOIN T_ORG_ORGANIZATIONS t8 on t8.FORGID = t1.FAPPLICATIONORGID	
                                                    INNER JOIN T_BD_MATERIAL T4 ON T4.FMATERIALID = t2.FWINECODE
                                                    INNER JOIN QUDE_t_StoresFiles_L t3 ON t3.FID = t1.F_QUDE_MERCHANT and t3.FLocaleID = @FLocaleId
                                                    INNER JOIN QUDE_t_StoresFiles t9 on t9.FID = t1.F_QUDE_MERCHANT
                                                    INNER JOIN T_ORG_ACCTSYSENTRY t10 ON t10.FMAINORGID= t8.FORGID
                                                    INNER JOIN T_ORG_ACCOUNTSYSTEM t13 on t13.FACCTSYSTEMID =t10.FACCTSYSTEMID AND t13.FISDEFAULT= 1 
                                                    INNER JOIN T_FA_ACCTPOLICY t11 ON t10.FDEFACCTPOLICY= t11.FACCTPOLICYID
                                                    INNER JOIN T_BD_CURRENCY t12 ON t12.FCURRENCYID= t11.FCURRENCYID  
                                                    INNER JOIN T_BD_CURRENCY_L t14 on t14.FCURRENCYID = t12.FCURRENCYID and t14.FLocaleID = @FLocaleId
			                                        left join (select  t1.FWINECODE as FWINECODE,t.FAPPLICATIONORGID as FAPPLICATIONORGID,max(t1.FPURCHASEPRICE) as FSELLINGPRICE
                                        from  QUDE_BiddingPurchaseOrder t 
                                        inner join QUDE_PurchaseOrderEntry t1 on t1.FID = t.FID and t.FTRANSACTIONS = 1 and t.FDOCUMENTSTATUS = 'C'
                                        group by t1.FWINECODE,t.FAPPLICATIONORGID
										)ts on ts.FWINECODE = t4.FMATERIALID and ts.FAPPLICATIONORGID = t1.FAPPLICATIONORGID
                                        left join (select sum(t.FBaseQty - isnull(t2.FBASEQTY,0))  as FBaseQty,t.FMATERIALID as FMATERIALID,FOWNERID as FOWNERID  
                                        from T_STK_INVENTORY  t
                                                    inner join T_BD_STOCK t1 on t1.FSTOCKID = t.FSTOCKID
                                                    left join 
                                                    (select sum (FBASEQTY) as FBASEQTY,FSUPPLYINTERID from T_PLN_RESERVELINKENTRY 
                                                    group by FSUPPLYINTERID
                                                    )t2 on t2.FSUPPLYINTERID = t.FID 
                                                    where  FOWNERTYPEID = 'BD_Customer' and  t.FBASEQTY <> 0
			                                        group by t.FMATERIALID,FOWNERID)kc on kc.FMATERIALID = t4.FMATERIALID and kc.FOWNERID = t9.FCUSTOMERID
                                    ");

                sbSql.AppendLine(@"  WHERE t1.FDOCUMENTSTATUS = 'C'");
                if (!string.IsNullOrWhiteSpace(BillNo))
                {
                    sbSql.AppendLine(" AND  t1.FBILLNO = @BillNo ");
                    lstParam.Add(new SqlParam("@BillNo", KDDbType.String, BillNo));
                }
                if (!string.IsNullOrWhiteSpace(OrgNumber))
                {
                    sbSql.AppendLine(" AND t8.FNUMBER =  @OrgNumber ");
                    lstParam.Add(new SqlParam("@OrgNumber", KDDbType.String, OrgNumber));
                }

                sbSql.AppendLine(" ) t ");//WHERE TI.FBASEQTY > 0

                sbSql.AppendFormat("/*dialect*/SELECT FIDENTITYID,  PurchaseOrderNo, TransNo, ApplicationDate, Submitdate,MerchantNumber, Merchant, Material, SalQty,SalAmount,ActualPrice,Servicerate,AllAmount,TransStatus,LogisticsStatus,CollectStatus,Currency,NewSalAmount,FBaseQty,SysMbol  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "竞价销售数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "竞价销售数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "竞价销售数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("竞价销售数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 竞价销售修改接口
        internal string UpDateBiddingSalesOrder(Context ctx, string Number, string TransStatus, int SalQty, string SalAmount, JObject result)
        {
            result["Result"] = false;
            try
            {
                string FID = "";
                string FEntryID = "";
                decimal FServiceRate = 0;
                string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //销售价格
                decimal FSalAmount = Convert.ToDecimal(SalAmount);
                string sql = string.Format(@"select  FServiceRate,t.FID AS FID,t1.FEntryID as FEntryID  from  QUDE_Bidding_SalesOrder t 
                                                inner join QUDE_Sale_OrderEntry t1 on t1.FID = t.FID 
                                                where FBILLNO = '{0}' and FDOCUMENTSTATUS = 'C' AND FTransactions <> 2", Number);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    //反审核
                    string UnAudit = "{\"Numbers\":[\"编码\"]}";
                    UnAudit = UnAudit.Replace("编码", Number);
                    object sub = WebApiServiceCall.UnAudit(ctx, "QUDE_BiddingSalesOrder", UnAudit);
                    FID = Convert.ToString(Datas.First()["FID"]);
                    FEntryID = Convert.ToString(Datas.First()["FEntryID"]);
                    FServiceRate = Convert.ToDecimal(Datas.First()["FServiceRate"]);
                    //实际销售价格
                    decimal FSellingPrice = FSalAmount * (1 - FServiceRate);
                    //总金额
                    decimal FTotalAmount = SalQty * FSellingPrice;
                    string save = CommonService.saleAllStr.Replace("主键", FID.ToString()).Replace("交易状态", TransStatus.ToString()).Replace("结束日期", date.ToString()).Replace("分录", FEntryID.ToString()).Replace("销售瓶数", SalQty.ToString()).Replace("实际销售价", FSellingPrice.ToString()).Replace("销售价格", FSalAmount.ToString()).Replace("总金额", FTotalAmount.ToString());
                    JObject resule = CommonService.SaveMethod(ctx, "QUDE_BiddingSalesOrder", save);
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        Number = CommonService.GetJParamString(resule, "Number");
                        JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", Number }
                                                                };

                        resule = CommonService.SubmitMethod(ctx, "QUDE_BiddingSalesOrder", jobj.ToString());
                        if (CommonService.GetJParamString(resule, "code") == "200")
                        {
                            resule = CommonService.AuditMethod(ctx, "QUDE_BiddingSalesOrder", jobj.ToString());
                            if (CommonService.GetJParamString(resule, "code") != "200")
                            {
                                result["Message"] = CommonService.GetJParamString(resule, "msg");
                            }
                            else
                            {
                                result["Result"] = true;
                                result["Message"] = "订单修改成功！";
                                JObject Data = new JObject();
                                Data.Add("BillNo", Number); //编码
                                result["Data"] = Data;

                            }
                        }
                        else
                        {
                            result["Message"] = CommonService.GetJParamString(resule, "msg");
                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }

                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = string.Format("销售单号：{0}返回查询结果为空！", Number);
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("订单查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 批量竞价销售修改接口JArray
        internal string AllUpDateBiddingSalesOrder(Context ctx, JObject jParams, JObject result)
        {
            result["Result"] = true;
            result["Message"] = "新增商品成功！";

            JArray SubEntity = new JArray();
            try
            {
                string FID = "";
                string FEntryID = "";
                decimal FServiceRate = 0;
                string Number = "";
                string TransStatus = "";
                string SalQty = "";
                string SalAmount = "";

                string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string sql = "";
                JArray FBillEntry = JArray.Parse(jParams["Data"].ToString());
                foreach (JObject List in FBillEntry)
                {
                    Number = List["Number"].ToString();
                    TransStatus = List["TransStatus"].ToString();
                    SalQty = List["SalQty"].ToString();
                    SalAmount = List["SalAmount"].ToString();
                    sql = string.Format(@"select  FServiceRate,t.FID AS FID,t1.FEntryID as FEntryID  from  QUDE_Bidding_SalesOrder t 
                                                inner join QUDE_Sale_OrderEntry t1 on t1.FID = t.FID 
                                                where FBILLNO = '{0}' and FDOCUMENTSTATUS = 'C' AND FTransactions <> 2", Number);
                    var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                    if (Datas != null && Datas.Count > 0)
                    {
                        ////反审核
                        //string UnAudit = "{\"Numbers\":[\"编码\"]}";
                        //UnAudit = UnAudit.Replace("编码", Number);
                        //object sub = WebApiServiceCall.UnAudit(ctx, "QUDE_BiddingSalesOrder", UnAudit);
                        FID = Convert.ToString(Datas.First()["FID"]);
                        FEntryID = Convert.ToString(Datas.First()["FEntryID"]);
                        FServiceRate = Convert.ToDecimal(Datas.First()["FServiceRate"]);
                        //实际销售价格
                        decimal FSalAmount = Convert.ToDecimal(SalAmount);
                        decimal FSellingPrice = FSalAmount * (1 - FServiceRate);
                        int FSalQty = Convert.ToInt32(SalQty);
                        //总金额
                        decimal FTotalAmount = FSalQty * FSellingPrice;
                        string save = CommonService.saleAllStr.Replace("主键", FID.ToString()).Replace("交易状态", TransStatus.ToString()).Replace("结束日期", date.ToString()).Replace("分录", FEntryID.ToString()).Replace("销售瓶数", FSalQty.ToString()).Replace("实际销售价", FSellingPrice.ToString()).Replace("销售价格", FSalAmount.ToString()).Replace("总金额", FTotalAmount.ToString());
                        JObject resule = CommonService.SaveMethod(ctx, "QUDE_BiddingSalesOrder", save);
                        if (CommonService.GetJParamString(resule, "code") == "200")
                        {
                            Number = CommonService.GetJParamString(resule, "Number");
                            JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", Number }
                                                                };

                            //resule = CommonService.SubmitMethod(ctx, "QUDE_BiddingSalesOrder", jobj.ToString());
                            //if (CommonService.GetJParamString(resule, "code") == "200")
                            //{
                            //    resule = CommonService.AuditMethod(ctx, "QUDE_BiddingSalesOrder", jobj.ToString());
                            //    if (CommonService.GetJParamString(resule, "code") != "200")
                            //    {
                            //        result["Message"] = CommonService.GetJParamString(resule, "msg");
                            //    }
                            //    else
                            //    {
                            result["Result"] = true;
                            result["Message"] = "订单修改成功！";
                            JObject Data = new JObject();
                            Data.Add("BillNo", Number); //编码
                            SubEntity.Add(Data);


                            //    }
                            //}
                            //else
                            //{
                            //    result["Message"] = CommonService.GetJParamString(resule, "msg");
                            //}
                        }
                        else
                        {
                            result["Message"] = CommonService.GetJParamString(resule, "msg");
                        }
                        result["Data"] = SubEntity;

                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = string.Format("销售单号：{0}返回查询结果为空！", Number);
                    }
                }

            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("订单修改成功失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 竞价采购修改接口
        internal string UpDateBiddingPurchaseOrder(Context ctx, string Number, string TransStatus, int FPurQty, string PurAmount, JObject result)
        {
            result["Result"] = false;
            try
            {
                string FID = "";
                string FEntryID = "";
                decimal FServiceRate = 0;
                string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //采购价格
                decimal FPurAmount = Convert.ToDecimal(PurAmount);
                string sql = string.Format(@"select  FServiceRate,t.FID AS FID,t1.FEntryID as FEntryID  from QUDE_BiddingPurchaseOrder t 
                                                inner join QUDE_PurchaseOrderEntry t1 on t1.FID = t.FID 
                                                where FBILLNO = '{0}' and FDOCUMENTSTATUS = 'C' AND FTransactions <> 2", Number);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    //反审核
                    string UnAudit = "{\"Numbers\":[\"编码\"]}";
                    UnAudit = UnAudit.Replace("编码", Number);
                    object sub = WebApiServiceCall.UnAudit(ctx, "QUDE_BiddingPurchaseOrder", UnAudit);
                    FID = Convert.ToString(Datas.First()["FID"]);
                    FEntryID = Convert.ToString(Datas.First()["FEntryID"]);
                    FServiceRate = Convert.ToDecimal(Datas.First()["FServiceRate"]);
                    //实际采购价格
                    decimal FSellingPrice = FPurAmount * (1 + FServiceRate); ;
                    //总金额
                    decimal FTotalAmount = FPurQty * FSellingPrice;
                    string save = CommonService.purchaseAllStr.Replace("主键", FID.ToString()).Replace("交易状态", TransStatus.ToString()).Replace("结束日期", date.ToString()).Replace("分录", FEntryID.ToString()).Replace("采购瓶数", FPurQty.ToString()).Replace("采购成本", FSellingPrice.ToString()).Replace("采购价格", FPurAmount.ToString()).Replace("总金额", FTotalAmount.ToString());
                    JObject resule = CommonService.SaveMethod(ctx, "QUDE_BiddingPurchaseOrder", save);
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        Number = CommonService.GetJParamString(resule, "Number");
                        JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", Number }
                                                                };

                        resule = CommonService.SubmitMethod(ctx, "QUDE_BiddingPurchaseOrder", jobj.ToString());
                        if (CommonService.GetJParamString(resule, "code") == "200")
                        {
                            resule = CommonService.AuditMethod(ctx, "QUDE_BiddingPurchaseOrder", jobj.ToString());
                            if (CommonService.GetJParamString(resule, "code") != "200")
                            {
                                result["Message"] = CommonService.GetJParamString(resule, "msg");
                            }
                            else
                            {
                                result["Result"] = true;
                                result["Message"] = "订单修改成功！";
                                JObject Data = new JObject();
                                Data.Add("BillNo", Number); //编码
                                result["Data"] = Data;

                            }
                        }
                        else
                        {
                            result["Message"] = CommonService.GetJParamString(resule, "msg");
                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }

                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = string.Format("采购单号：{0}返回查询结果为空！", Number);
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("订单查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 竞价采购新增接口
        internal string BiddingPurchaseOrder(Context ctx, string OrgNumber, string MerchantNumber, string Material, string Date, int FPurQty, string PurAmount, JObject result)
        {
            result["Result"] = false;
            try
            {
                decimal FServiceRate = 0;
                int FORGID = 0;
                string FBCurrencyId = string.Empty;
                DateTime curdate = DateTime.Now;
                string StockNumber = string.Empty;
                string SQL = string.Format("SELECT FORGID FROM T_ORG_ORGANIZATIONS WHERE FNUMBER = '{0}'", OrgNumber);
                DynamicObjectCollection dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    FORGID = Convert.ToInt32(dynamicObjects.First()["FORGID"]);
                }
                //SQL = string.Format(@"/*dialect*/SELECT
                //                                    TOP 1 t1.FBILLNO as FBILLNO
                //                                    FROM
                //                                    QUDE_Bidding_SalesOrder t1 
                //                                    INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID
                //                                    INNER JOIN T_BD_MATERIAL T3 ON T3.FMATERIALID = T2.FWINECODE
                //                                    INNER JOIN QUDE_t_StoresFiles T4 ON T4.FID = T1.F_QUDE_MERCHANT
                //                                    INNER JOIN T_ORG_ORGANIZATIONS T5 ON T5.FORGID = T1.FAPPLICATIONORGID
                //                                    WHERE
                //                                    t3.FNUMBER = '{0}'
                //                                    AND T1.FTRANSACTIONS IN(1,3)
                //                                    AND T4.FNUMBER = '{1}'
                //                                    AND T5.FNUMBER = '{2}'", Material, MerchantNumber, OrgNumber);

                //dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                //if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                //{
                //    StockNumber = dynamicObjects.First()["FBILLNO"].ToString();
                //    result["Message"] = string.Format("已发布销售订单：'{0}'!", StockNumber);
                //    return result.ToString();
                //}

                SQL = string.Format(@"/*dialect*/SELECT
                                                    TOP 1 t1.FBILLNO as FBILLNO
                                                    FROM
                                                    QUDE_BiddingPurchaseOrder t1 
                                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t1.FID = t2.FID
                                                    INNER JOIN T_BD_MATERIAL T3 ON T3.FMATERIALID = T2.FWINECODE
                                                    INNER JOIN QUDE_t_StoresFiles T4 ON T4.FID = T1.F_QUDE_MERCHANT
                                                    INNER JOIN T_ORG_ORGANIZATIONS T5 ON T5.FORGID = T1.FAPPLICATIONORGID
                                                    WHERE
                                                    t3.FNUMBER = '{0}'
                                                    AND T1.FTRANSACTIONS IN(1,3)
                                                    AND T4.FNUMBER = '{1}'
                                                    AND T5.FNUMBER = '{2}'", Material, MerchantNumber, OrgNumber);

                dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    StockNumber = dynamicObjects.First()["FBILLNO"].ToString();
                    result["Message"] = string.Format("已发布采购订单：'{0}'!", StockNumber);
                    return result.ToString();
                }

                SQL = string.Format(@"/*dialect*/SELECT
	                                                            t1.FNUMBER 
                                                            FROM
	                                                            T_BD_STOCK t1
                                                            WHERE
	                                                            FUSEORGID = {0}", FORGID);

                dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    StockNumber = dynamicObjects.First()["FNUMBER"].ToString();
                }
                SQL = string.Format(@"/*dialect*/SELECT
	                                                            t2.FNUMBER 
                                                            FROM
	                                                            t_BD_MaterialStock t1
	                                                            LEFT JOIN T_BD_CURRENCY t2 ON t1.FCURRENCYID = t2.FCURRENCYID
                                                                LEFT JOIN T_BD_MATERIAL t3 on t3.FMATERIALID = t1.FMATERIALID
                                                            WHERE
	                                                            t3.FNUMBER = '{0}'", Material);

                dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    FBCurrencyId = dynamicObjects.First()["FNUMBER"].ToString();
                }

                SQL = string.Format(@"/*dialect*/SELECT
                                                                F_QUDE_SalesFee 
                                                            FROM
                                                                ora_t_Patformparameter
                                                            WHERE F_ORA_ORGID = {0}
                                                            ", FORGID);

                dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    FServiceRate = Convert.ToDecimal(dynamicObjects.First()["F_QUDE_SalesFee"]);
                }
                decimal FPurAmount = Convert.ToDecimal(PurAmount);
                decimal FSellingPrice = FPurAmount * (1 + FServiceRate);

                decimal FTotalAmount = FPurQty * FSellingPrice;
                string purchaseStr = CommonService.purchaseStr.Replace("发布日期", Date).Replace("发布区域", OrgNumber).Replace("商家信息", MerchantNumber).
                                                               Replace("出货仓库", StockNumber).Replace("结束日期", curdate.AddMonths(2).ToString("yyyy-MM-dd 00:00:00")).Replace("开始日期", Date).Replace("采购瓶数", FPurQty.ToString()).
                                                               Replace("酒款编码", Material).Replace("采购成本", FSellingPrice.ToString()).Replace("采购价格", FPurAmount.ToString()).Replace("总金额", FTotalAmount.ToString()).Replace("结算币别", FBCurrencyId).Replace("服务费率", FServiceRate.ToString());
                JObject resule = CommonService.SaveMethod(ctx, "QUDE_BiddingPurchaseOrder", purchaseStr);
                if (CommonService.GetJParamString(resule, "code") == "200")
                {
                    string Number = CommonService.GetJParamString(resule, "Number");
                    JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", Number }
                                                                };

                    resule = CommonService.SubmitMethod(ctx, "QUDE_BiddingPurchaseOrder", jobj.ToString());
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        resule = CommonService.AuditMethod(ctx, "QUDE_BiddingPurchaseOrder", jobj.ToString());
                        if (CommonService.GetJParamString(resule, "code") != "200")
                        {
                            result["Message"] = CommonService.GetJParamString(resule, "msg");
                        }
                        else
                        {
                            result["Result"] = true;
                            result["Message"] = "新增采购订单成功！";
                            JObject Data = new JObject();
                            Data.Add("BillNo", Number); //编码
                            result["Data"] = Data;

                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }
                }
                else
                {
                    result["Message"] = CommonService.GetJParamString(resule, "msg");
                }

            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("订单查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion


        #region 竞价销售新增接口
        internal string BiddingSalesOrder(Context ctx, string OrgNumber, string MerchantNumber, string Material, string Date, int FSalQty, string SalAmount, JObject result)
        {
            result["Result"] = false;
            try
            {
                decimal FServiceRate = 0;
                int FORGID = 0;
                string FBCurrencyId = string.Empty;
                DateTime curdate = DateTime.Now;
                string StockNumber = string.Empty;
                string SQL = string.Format("SELECT FORGID FROM T_ORG_ORGANIZATIONS WHERE FNUMBER = '{0}'", OrgNumber);
                DynamicObjectCollection dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    FORGID = Convert.ToInt32(dynamicObjects.First()["FORGID"]);
                }
                //SQL = string.Format(@"/*dialect*/SELECT
                //                                    TOP 1 t1.FBILLNO as FBILLNO
                //                                    FROM
                //                                    QUDE_BiddingPurchaseOrder t1 
                //                                    INNER JOIN QUDE_PurchaseOrderEntry t2 ON t1.FID = t2.FID
                //                                    INNER JOIN T_BD_MATERIAL T3 ON T3.FMATERIALID = T2.FWINECODE
                //                                    INNER JOIN QUDE_t_StoresFiles T4 ON T4.FID = T1.F_QUDE_MERCHANT
                //                                    INNER JOIN T_ORG_ORGANIZATIONS T5 ON T5.FORGID = T1.FAPPLICATIONORGID
                //                                    WHERE
                //                                    t3.FNUMBER = '{0}'
                //                                    AND T1.FTRANSACTIONS IN(1,3)
                //                                    AND T4.FNUMBER = '{1}'
                //                                    AND T5.FNUMBER = '{2}'", Material,MerchantNumber, OrgNumber);

                //dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                //if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                //{
                //    StockNumber = dynamicObjects.First()["FBILLNO"].ToString();
                //    result["Message"] = string.Format("已发布采购订单：'{0}'!", StockNumber);
                //    return result.ToString();
                //}
                SQL = string.Format(@"/*dialect*/SELECT
                                                    TOP 1 t1.FBILLNO as FBILLNO
                                                    FROM
                                                    QUDE_Bidding_SalesOrder t1 
                                                    INNER JOIN QUDE_Sale_OrderEntry t2 ON t1.FID = t2.FID
                                                    INNER JOIN T_BD_MATERIAL T3 ON T3.FMATERIALID = T2.FWINECODE
                                                    INNER JOIN QUDE_t_StoresFiles T4 ON T4.FID = T1.F_QUDE_MERCHANT
                                                    INNER JOIN T_ORG_ORGANIZATIONS T5 ON T5.FORGID = T1.FAPPLICATIONORGID
                                                    WHERE
                                                    t3.FNUMBER = '{0}'
                                                    AND T1.FTRANSACTIONS IN(1,3)
                                                    AND T4.FNUMBER = '{1}'
                                                    AND T5.FNUMBER = '{2}'", Material, MerchantNumber, OrgNumber);

                dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    StockNumber = dynamicObjects.First()["FBILLNO"].ToString();
                    result["Message"] = string.Format("已发布销售订单：'{0}'!", StockNumber);
                    return result.ToString();
                }
                SQL = string.Format(@"/*dialect*/SELECT
	                                                            t1.FNUMBER 
                                                            FROM
	                                                            T_BD_STOCK t1
                                                            WHERE
	                                                            FUSEORGID = {0}", FORGID);

                dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    StockNumber = dynamicObjects.First()["FNUMBER"].ToString();
                }
                SQL = string.Format(@"/*dialect*/SELECT
	                                                            t2.FNUMBER 
                                                            FROM
	                                                            t_BD_MaterialStock t1
	                                                            LEFT JOIN T_BD_CURRENCY t2 ON t1.FCURRENCYID = t2.FCURRENCYID
                                                                LEFT JOIN T_BD_MATERIAL t3 on t3.FMATERIALID = t1.FMATERIALID
                                                            WHERE
	                                                            t3.FNUMBER = '{0}'", Material);

                dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    FBCurrencyId = dynamicObjects.First()["FNUMBER"].ToString();
                }

                SQL = string.Format(@"/*dialect*/SELECT
                                                                F_QUDE_SalesFee 
                                                            FROM
                                                                ora_t_Patformparameter
                                                            WHERE F_ORA_ORGID = {0}
                                                            ", FORGID);

                dynamicObjects = DBUtils.ExecuteDynamicObject(ctx, SQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((dynamicObjects != null) && (dynamicObjects.Count > 0))
                {
                    FServiceRate = Convert.ToDecimal(dynamicObjects.First()["F_QUDE_SalesFee"]);
                }
                decimal FSalAmount = Convert.ToDecimal(SalAmount);
                decimal FSellingPrice = FSalAmount * (1 - FServiceRate);

                decimal FTotalAmount = FSalQty * FSellingPrice;
                string saleStr = CommonService.saleStr.Replace("发布日期", curdate.ToString("yyyy-MM-dd 00:00:00")).Replace("发布区域", OrgNumber).Replace("商家信息", MerchantNumber).
                                                                                   Replace("出货仓库", StockNumber).Replace("结束日期", curdate.AddMonths(2).ToString("yyyy-MM-dd 00:00:00")).Replace("开始日期", curdate.ToString("yyyy-MM-dd 00:00:00")).Replace("销售瓶数", FSalQty.ToString()).
                                                                                   Replace("酒款编码", Material).Replace("实际销售价", FSellingPrice.ToString()).Replace("销售价格", SalAmount.ToString()).Replace("总金额", FTotalAmount.ToString()).Replace("结算币别", FBCurrencyId).Replace("服务费率", FServiceRate.ToString());
                JObject resule = CommonService.SaveMethod(ctx, "QUDE_BiddingSalesOrder", saleStr);
                if (CommonService.GetJParamString(resule, "code") == "200")
                {
                    string Number = CommonService.GetJParamString(resule, "Number");
                    JObject jobj = new JObject
                                                                {
                                                                    { "Numbers", Number }
                                                                };

                    resule = CommonService.SubmitMethod(ctx, "QUDE_BiddingSalesOrder", jobj.ToString());
                    if (CommonService.GetJParamString(resule, "code") == "200")
                    {
                        resule = CommonService.AuditMethod(ctx, "QUDE_BiddingSalesOrder", jobj.ToString());
                        if (CommonService.GetJParamString(resule, "code") != "200")
                        {
                            result["Message"] = CommonService.GetJParamString(resule, "msg");
                        }
                        else
                        {
                            result["Result"] = true;
                            result["Message"] = "新增销售订单成功！";
                            JObject Data = new JObject();
                            Data.Add("BillNo", Number); //编码
                            result["Data"] = Data;

                        }
                    }
                    else
                    {
                        result["Message"] = CommonService.GetJParamString(resule, "msg");
                    }
                }
                else
                {
                    result["Message"] = CommonService.GetJParamString(resule, "msg");
                }

            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("订单查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion




        //查询物料信息
        internal string MallRepairOrder(Context ctx, string FBILLNO, string FMAINTENANCEAMOUNT, string FBUSINESSSTATUS, string FMAILINGNUMBER, string FRECIPIENTNAME, string FRECIPIENTPHONE, string FRETURNADDRESS, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = "";
                if (!string.IsNullOrWhiteSpace(FMAINTENANCEAMOUNT))
                {
                    sql = string.Format(@"update ora_MallRepairOrder set FMAINTENANCEAMOUNT = '{0}' where FBILLNO = '{1}'", FMAINTENANCEAMOUNT, FBILLNO);
                    DBUtils.Execute(ctx, sql);
                }
                if (!string.IsNullOrWhiteSpace(FBUSINESSSTATUS))
                {
                    sql = string.Format(@"update ora_MallRepairOrder set FBUSINESSSTATUS = '{0}' where FBILLNO = '{1}'", FBUSINESSSTATUS, FBILLNO);
                    DBUtils.Execute(ctx, sql);
                }
                if (!string.IsNullOrWhiteSpace(FMAILINGNUMBER))
                {
                    sql = string.Format(@"update ora_MallRepairOrder set FMAILINGNUMBER = '{0}' where FBILLNO = '{1}'", FMAILINGNUMBER, FBILLNO);
                    DBUtils.Execute(ctx, sql);
                }
                if (!string.IsNullOrWhiteSpace(FRECIPIENTNAME))
                {
                    sql = string.Format(@"update ora_MallRepairOrder set FRECIPIENTNAME = '{0}' where FBILLNO = '{1}'", FRECIPIENTNAME, FBILLNO);
                    DBUtils.Execute(ctx, sql);
                }
                if (!string.IsNullOrWhiteSpace(FRECIPIENTPHONE))
                {
                    sql = string.Format(@"update ora_MallRepairOrder set FRECIPIENTPHONE = '{0}' where FBILLNO = '{1}'", FRECIPIENTPHONE, FBILLNO);
                    DBUtils.Execute(ctx, sql);
                }
                if (!string.IsNullOrWhiteSpace(FRETURNADDRESS))
                {
                    sql = string.Format(@"update ora_MallRepairOrder set FRETURNADDRESS = '{0}' where FBILLNO = '{1}'", FRETURNADDRESS, FBILLNO);
                    DBUtils.Execute(ctx, sql);
                }
                result["Result"] = true;
                result["Message"] = "更新成功";
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("物料信息查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        //查询物料信息
        internal string QueryMaterialInfo(Context ctx, string Fnumber, JObject result)
        {
            result["Result"] = false;
            try
            {
                string sql = string.Format(@"select t1.FNUMBER as FNumber,t2.FNAME as FName,t5.FNUMBER as FUNITNUMBER,t6.FNAME  as FUNITNAME,
                t3.FGOODBARCODE_CMK as FBarCode,t3.FSalePrice_CMK as FSalePrice 
                from T_BD_MATERIAL t1
                inner join T_BD_MATERIAL_L t2 on t2.FMATERIALID = t1.FMATERIALID
                inner join CMK_BD_MATERIAL t3 on t3.FMATERIALID = t1.FMATERIALID
				left join t_BD_MaterialBase t4 on t4.FMATERIALID = t1.FMATERIALID
				left join T_BD_UNIT t5 on t5.FUNITID = t4.FBASEUNITID
				left join T_BD_UNIT_L t6 on t6.FUNITID = t5.FUNITID and t6.FLOCALEID = 2052
                where t2.FLOCALEID = 2052 and t1.FMASTERID = t1.FMATERIALID and  t1.FNUMBER = '{0}'", Fnumber);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, sql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "物料信息查询成功";

                    JObject Data = new JObject();
                    var dataMaterial = Datas.First();
                    Data.Add("FNumber", Convert.ToString(dataMaterial["FNumber"])); //编码
                    Data.Add("FName", Convert.ToString(dataMaterial["FName"]));//名称
                    Data.Add("FBarCode", Convert.ToString(dataMaterial["FBarCode"]));//条形码
                    Data.Add("FUNITNUMBER", Convert.ToString(dataMaterial["FUNITNUMBER"]));
                    Data.Add("FUNITNAME", Convert.ToString(dataMaterial["FUNITNAME"]));
                    Data.Add("FSalePrice", Convert.ToString(dataMaterial["FSalePrice"]));//零售价格
                    result["Data"] = Data;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "物料息查询完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("物料信息查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        #region 会员关键信息查询
        internal string QueryVIPMemberKeyValue(Context ctx, string CardNo, string MobileNo, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();

                sbSql.AppendLine("SELECT FMobile, FCardNo, FTimeStamp FROM ");
                sbSql.AppendLine("(SELECT TOP 1 t1.FMobile, t2.FNUMBER AS FCardNo, ");
                sbSql.AppendLine("     ISNULL(CONVERT(INT, CASE WHEN t1.FTimeStamp > t2.FTimeStamp THEN t1.FTimeStamp ELSE t2.FTimeStamp END), 0) AS FTimeStamp ");
                sbSql.AppendLine("FROM CMK_T_VIP_Member t1 INNER JOIN CMK_T_VIP_CARD t2 ON t2.FVIPMemberID = t1.FVIPID ");
                sbSql.AppendLine("    WHERE 1 = 1 ");

                if (!string.IsNullOrWhiteSpace(CardNo))
                {
                    sbSql.AppendLine(" AND t2.FNumber = @CardNo ");
                    lstParam.Add(new SqlParam("@CardNo", KDDbType.String, CardNo));
                }

                if (!string.IsNullOrWhiteSpace(MobileNo))
                {
                    sbSql.AppendLine(" AND t1.FMobile = @MobileNo ");
                    lstParam.Add(new SqlParam("@MobileNo", KDDbType.String, MobileNo));
                }
                sbSql.AppendLine(") t ");

                var Datas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "会员关键信息查询成功";

                    JObject Data = new JObject();
                    var dataVip = Datas.First();
                    Data.Add("FMobile", Convert.ToString(dataVip["FMobile"]));
                    Data.Add("FCardNo", Convert.ToString(dataVip["FCardNo"]));

                    var FTimeStamp = "0";
                    if (dataVip["FTimeStamp"] != null)
                    {
                        FTimeStamp = Convert.ToInt64(dataVip["FTimeStamp"]).ToString("X8");
                    }
                    Data.Add("FTimeStamp", string.Format("0x{0}", FTimeStamp.PadLeft(16, '0')));
                    result["Data"] = Data;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "会员关键信息查询完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("会员关键信息查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 会员信息查询
        internal string QueryVIPMemberInfo(Context ctx, string CardNo, string MobileNo, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();

                sbSql.AppendLine("SELECT FVIPBranch, FCreateDate, FVIPId, FNumber, FName, FSex, FBirthday, FIDType, FIDNumber, FTel, FMobile, FWeixin, FQQ, FEmail, FSource, ");
                sbSql.AppendLine("    FNation, FCountry, FProvince, FCity, FCounty, FEducation, FBusinessArea, FCommunity, FConsumeCount, FConsumeAmount, FReturnCount, FReturnAmount, FTimeStamp FROM ");
                sbSql.AppendLine("(SELECT TOP 1 ISNULL(t4.FName, '') AS FVIPBranch, TO_CHAR(t1.FCreateDate, 'yyyy-MM-dd') AS FCreateDate, t1.FVIPId, t1.FNumber, t2.FName, ISNULL(t11.FDataValue, '') AS FSex, TO_CHAR(t1.FBirthday, 'yyyy-MM-dd') AS FBirthday, ");
                sbSql.AppendLine("    ISNULL(t8.FDataValue, '') AS FIDType, t1.FIDNumber, t1.FTel, t1.FMobile, t1.FWeixin, t1.FQQ, t1.FEmail, ISNULL(t17.FDataValue, '') AS FSource, ");
                sbSql.AppendLine("    ISNULL(t10.FDataValue, '') AS FNation, ISNULL(t21.FDataValue, '') AS FCountry, ISNULL(t22.FDataValue, '') AS FProvince, ISNULL(t23.FDataValue, '') AS FCity, ISNULL(t24.FDataValue, '') AS FCounty, ");
                sbSql.AppendLine("    ISNULL(t14.FDataValue, '') AS FEducation, ISNULL(t15.FDataValue, '') AS FBusinessArea, ISNULL(t16.FDataValue, '') AS FCommunity, ");
                sbSql.AppendLine("    t1.FConsumeCount, t1.FConsumeAmount, t1.FReturnCount, t1.FReturnAmount, ISNULL(CONVERT(INT, CASE WHEN t1.FTimeStamp > t3.FTimeStamp THEN t1.FTimeStamp ELSE t3.FTimeStamp END), 0) AS FTimeStamp ");
                sbSql.AppendLine("FROM CMK_T_VIP_Member t1 INNER JOIN CMK_T_VIP_Member_L t2 ON t1.FVIPID = t2.FVIPID AND t2.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARD t3 ON t3.FVIPMemberID = t1.FVIPID ");
                sbSql.AppendLine("    LEFT JOIN CMK_LS_Branch_L t4 ON t4.FID = t1.FBranchID AND t4.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t8 ON t1.FIDType = t8.FEntryID AND t8.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t10 ON t1.FNationality = t10.FEntryID AND t10.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t11 ON t1.FSex = t11.FEntryID AND t11.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t14 ON t1.FEducation = t14.FEntryID AND t14.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t15 ON t1.FBusinessArea = t15.FEntryID AND t15.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t16 ON t1.FCommunity = t16.FEntryID AND t16.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t17 ON t1.FVIPWhereFrom = t17.FEntryID AND t17.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_ECC_LOGISTICSAREADETAIL_L t21 ON t1.FCountryID = t21.FDetailId AND t21.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_ECC_LOGISTICSAREADETAIL_L t22 ON t1.FRegionID = t22.FDetailId AND t22.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_ECC_LOGISTICSAREADETAIL_L t23 ON t1.FCityID = t23.FDetailId AND t23.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_ECC_LOGISTICSAREADETAIL_L t24 ON t1.FCountyID = t24.FDetailId AND t24.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("WHERE 1 = 1 ");

                if (!string.IsNullOrWhiteSpace(CardNo))
                {
                    sbSql.AppendLine(" AND t3.FNumber = @CardNo ");
                    lstParam.Add(new SqlParam("@CardNo", KDDbType.String, CardNo));
                }

                if (!string.IsNullOrWhiteSpace(MobileNo))
                {
                    sbSql.AppendLine(" AND t1.FMobile = @MobileNo ");
                    lstParam.Add(new SqlParam("@MobileNo", KDDbType.String, MobileNo));
                }
                sbSql.AppendLine(") t ");

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var vipData = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (vipData != null && vipData.Count > 0)
                {
                    JObject jVipData = JObject.FromObject(vipData.First());

                    var FTimeStamp = "0";
                    if (jVipData["FTimeStamp"] != null)
                    {
                        FTimeStamp = Convert.ToInt64(CommonService.GetJParamString(jVipData, "FTimeStamp")).ToString("X8");
                    }
                    jVipData["FTimeStamp"] = string.Format("0x{0}", FTimeStamp.PadLeft(16, '0'));

                    JObject resCard = new JObject();
                    resCard.Add("Result", false);
                    resCard.Add("Message", "");
                    resCard.Add("Data", string.Empty);

                    this.QueryVIPCardInfo(ctx, CardNo, MobileNo, resCard);
                    jVipData.Add("Card", resCard["Data"]);

                    result["Result"] = true;
                    result["Message"] = "会员信息查询成功";
                    result["Data"] = jVipData;
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "会员信息查询完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("会员信息查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 会员卡信息查询
        internal string QueryVIPCardInfo(Context ctx, string CardNo, string MobileNo, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                sbSql.AppendLine("SELECT FBranch, FVIPName, FCardId, FCardNo, FCardType, FCardLevelNumber, FCardLevelName, FCardMedia,  FCardStatus, FFreezeStatus FROM ");
                sbSql.AppendLine("(SELECT TOP 20 ISNULL(t4.FName, '') AS FBranch, ISNULL(t3.FName, '') AS FVIPName, t1.FCardId, t1.FNumber AS FCardNo, ");
                sbSql.AppendLine("    ISNULL(t5.FName, '') AS FCardType, ISNULL(t6.FSGNumber, '') AS FCardLevelNumber, ISNULL(t6_l.FName, '') AS FCardLevelName, ISNULL(t7.FDataValue, '') AS FCardMedia, ");
                sbSql.AppendLine("    t1.FValidControl, CONVERT(varchar(100), t1.FDateStart, 120) AS FDateStart, CONVERT(varchar(100), t1.FDateEnd, 120) AS FDateEnd, ");
                sbSql.AppendLine("    CASE t1.FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus, ");
                sbSql.AppendLine("    CASE t1.FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus  ");
                sbSql.AppendLine("FROM CMK_T_VIP_CARD t1 LEFT JOIN CMK_T_VIP_Member t2 ON t1.FVIPMemberID = t2.FVIPID ");
                sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_Member_L t3 ON t2.FVIPID = t3.FVIPID AND t3.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN CMK_LS_Branch_L t4 ON t4.FID = t1.FBranchID AND t4.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARDTYPE_L t5 ON t5.FCardTypeID = t1.FCardTypeID AND t5.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARDLEVEL t6 ON t6.FCardLevelID = t1.FCardLevelID ");
                sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARDLEVEL_L t6_l ON t6_l.FCardLevelID = t1.FCardLevelID AND t6_l.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t7 ON t7.FEntryID = t1.FCardMedia AND t7.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("WHERE 1 = 1 ");

                if (!string.IsNullOrWhiteSpace(CardNo))
                {
                    sbSql.AppendLine(" AND t1.FNumber = @CardNo ");
                    lstParam.Add(new SqlParam("@CardNo", KDDbType.String, CardNo));
                }

                if (!string.IsNullOrWhiteSpace(MobileNo))
                {
                    sbSql.AppendLine(" AND t2.FMobile = @MobileNo ");
                    lstParam.Add(new SqlParam("@MobileNo", KDDbType.String, MobileNo));
                }
                sbSql.AppendLine(") t ");

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, 2052));
                DataSet cardDatas = XDDDBUtils.ExecuteDateSet(sbSql.ToString(), lstParam);
                //var cardDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (cardDatas != null && cardDatas.Tables.Count > 0 && cardDatas.Tables[0].Rows.Count > 0)
                {
                    JArray XData = JArray.FromObject(cardDatas.Tables[0]);
                    foreach (JObject cardData in XData)
                    {
                        sbSql.Clear();
                        lstParam = new List<SqlParam>();
                        sbSql.AppendLine("SELECT FCardNo, FCardId, FAccountId, FAcctName, FValue, FAcctType FROM ");
                        sbSql.AppendLine("(SELECT TOP 20 t4.FNumber AS FCardNo, t1.FCardId, t1.FAccountId, ISNULL(t3.FName, '') AS FAcctName, CAST(t1.FValue * 100 as int) as FValue, CASE WHEN t2.FAcctType = 'A' THEN '积分账户' ELSE '金额账户' END AS FAcctType, ");
                        sbSql.AppendLine("    t1.FAcctValidCtrl, CONVERT(varchar(100), t1.FAcctDateStart, 23) AS FAcctDateStart, CONVERT(varchar(100), t1.FAcctDateEnd, 23) AS FAcctDateEnd ");
                        sbSql.AppendLine("FROM CMK_T_VIP_CARDACCTS t1 LEFT JOIN CMK_T_VIP_CARDACCT t2 ON t1.FAccountID = t2.FCardAcctID ");
                        sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARDACCT_L t3 ON t2.FCardAcctID = t3.FCardAcctID AND t3.FLocaleId = @FLocaleId ");
                        sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARD t4 ON t1.FCardId = t4.FCardId ");
                        sbSql.AppendLine("WHERE t1.FCardId IN (@CardIds) and t1.FAccountId = 2 ) t ");
                        lstParam.Add(new SqlParam("@CardIds", KDDbType.String, cardData["FCardId"].ToString()));//JCard.GetInt64("FCardId")// cardDatas["FCardId"].ToString()
                        lstParam.Add(new SqlParam("@FLocaleID", KDDbType.Int32, "2052"));

                        DataSet cardAccts = XDDDBUtils.ExecuteDateSet(sbSql.ToString(), lstParam);
                        if (cardAccts != null && cardAccts.Tables.Count > 0 && cardAccts.Tables[0].Rows.Count > 0)
                        {
                            cardData.Add("Accts", JArray.FromObject(cardAccts.Tables[0]));
                        }

                        result["Result"] = true;
                        result["Message"] = "会员卡信息查询成功";
                        result["Data"] = XData;
                    }
                }
                else
                {
                    result["Result"] = false;
                    result["Message"] = "会员卡信息查询完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("会员卡信息查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 卡储值积分交易数据查询
        internal string QueryVIPCardConsumeData(Context ctx, string BeginDate, string EndDate, string CardNo, long AccountId, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("SELECT FCardNo, FSumConsumAmt, FBranchName, FBillNo, FDate, FAccountId, FOption, FOperValue, FBalance, FOperationType, FNote, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FAccountId, FDate DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine("(SELECT TOP 200 t1.FNUMBER AS FCardNo, CONVERT(DECIMAL(20, 2), t1.FSumConsumAmt) AS FSumConsumAmt, ");
                sbSql.AppendLine("   ISNULL(t3.FNAME, '') AS FBranchName, t2.FBillNo, TO_CHAR(t2.FRECORDDATETIME, 'yyyy-MM-dd HH24:mi:ss') AS FDate, t2.FAccountId, t2.FOption, ");
                sbSql.AppendLine("   CONVERT(DECIMAL(20, 2), t2.FOperValue) AS FOperValue, CONVERT(DECIMAL(20, 2), t2.FBalance) AS FBalance, t2.FOperationType, ISNULL(t4l.FDATAVALUE, '') AS FNote ");
                sbSql.AppendLine("FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_VIP_T_CardAction t2 ON t1.FCardID = t2.FCARDID ");
                sbSql.AppendLine("   LEFT JOIN CMK_LS_Branch_L t3 ON t2.FBranchID = t3.FID AND t3.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("   LEFT JOIN T_BAS_ASSISTANTDATAENTRY t4 ON t2.FIntegralType = t4.FNumber AND t4.FID = 'xh6c06b51cc4a13a11e484d345759d8e' ");
                sbSql.AppendLine("   LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t4l ON t4.FEntryID = t4l.FEntryID AND t4l.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("WHERE t2.FACCOUNTID IN (1, 2, 4) AND t2.FOPERVALUE > 0 AND t1.FNumber = @CardNo ");
                if (AccountId > 0)
                {
                    sbSql.AppendLine(" AND FACCOUNTID = @AccountId ");
                    lstParam.Add(new SqlParam("@AccountId", KDDbType.Int64, AccountId));
                }

                if (!string.IsNullOrWhiteSpace(BeginDate))
                {
                    sbSql.AppendLine(" AND t2.FRECORDDATETIME >= @BeginDate ");
                    lstParam.Add(new SqlParam("@BeginDate", KDDbType.String, BeginDate));
                }

                if (!string.IsNullOrWhiteSpace(EndDate))
                {
                    sbSql.AppendLine(" AND t2.FRECORDDATETIME <= @EndDate ");
                    lstParam.Add(new SqlParam("@EndDate", KDDbType.String, EndDate));
                }
                sbSql.AppendLine(" ) t ");

                sbSql.AppendFormat("SELECT FIDENTITYID, FCardNo, FSumConsumAmt, FBranchName, FBillNo, FDate, FAccountId, FOption, FOperValue, FBalance, FOperationType, FNote FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@CardNo", KDDbType.String, CardNo));
                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int TotalPage = 0;
                    int TotalCount = TotalDatas.Count;

                    iPageSize = iPageSize <= 0 ? TotalDatas.Count : iPageSize;
                    TotalPage = (int)Math.Ceiling(Convert.ToDecimal(TotalCount) / iPageSize);
                    iPageNum = iPageNum <= 0 ? 1 : iPageNum;
                    iPageNum = iPageNum > TotalPage ? TotalPage : iPageNum;

                    iBNum = iPageSize * (iPageNum - 1) + 1;
                    iENum = iPageSize * (iPageNum);

                    JObject Data = new JObject();
                    Data.Add("TotalCount", TotalCount);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", TotalPage);
                    Data.Add("CurPage", iPageNum);

                    var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "卡储值积分交易数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "卡储值积分交易数据查询完成，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "卡储值积分交易数据查询完成，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("卡储值积分交易数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 库存对比数据查询
        internal string QueryMaterial(Context ctx, int iPageSize, int iPageNum, string FMaterialId, string FStockId, string FVkNumber, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("SELECT FstockOrgId, FstockOrgname, FMaterialId, FMaterialName, FStockId, FStockName, FBaseQty, ");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FstockOrgId, FStockId DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@"(SELECT
                                    TI.FSTOCKORGID AS FstockOrgId,
                                    OL.FNAME  AS FstockOrgname,
                                    M.FTHIRDBILLNO AS FMaterialId, --物料编码
                                    ML.FNAME AS FMaterialName, --物料名称
                                    TSK.FTHIRDBILLNO AS FStockId,
                                    TSL.FNAME AS FStockName, --仓库
                                    TI.FBASEQTY AS FBaseQty
                                    FROM T_STK_INVENTORY TI
                                    LEFT OUTER JOIN T_ORG_ORGANIZATIONS_L OL ON(TI.FSTOCKORGID = OL.FORGID AND OL.FLOCALEID = 2052)--机构名称
                                    INNER JOIN T_BD_MATERIAL M ON(M.FMASTERID = TI.FMATERIALID AND(M.FUSEORGID = TI.FSTOCKORGID OR EXISTS(SELECT 1 FROM T_META_BASEDATATYPE BT WHERE(BT.FBASEDATATYPEID = 'BD_MATERIAL' AND BT.FSTRATEGYTYPE = 1))))--物料
                                    LEFT OUTER JOIN T_BD_MATERIAL_L ML ON(M.FMATERIALID = ML.FMATERIALID AND ML.FLOCALEID = 2052)--物料名称、规格型号
                                    INNER JOIN T_BD_MATERIALSTOCK TMS ON M.FMATERIALID = TMS.FMATERIALID
                                    LEFT OUTER JOIN T_ENG_BOM TB ON(TB.FMASTERID = TI.FBOMID AND(TB.FUSEORGID = TI.FSTOCKORGID OR EXISTS(SELECT 1 FROM T_META_BASEDATATYPE BT WHERE(BT.FBASEDATATYPEID = 'ENG_BOM' AND BT.FSTRATEGYTYPE = 1))))
                                    LEFT OUTER JOIN T_BD_STOCKSTATUS_L TSSL ON(TI.FSTOCKSTATUSID = TSSL.FSTOCKSTATUSID AND TSSL.FLOCALEID = 2052)
                                    LEFT OUTER JOIN T_BD_LOTMASTER TL ON((TI.FLOT = TL.FMASTERID AND TI.FSTOCKORGID = TL.FUSEORGID) AND TL.FBIZTYPE = '1')
                                    LEFT OUTER JOIN T_BD_UNIT TUS ON TMS.FSTOREUNITID = TUS.FUNITID
                                    LEFT OUTER JOIN T_BD_UNIT_L TUL0 ON(TMS.FSTOREUNITID = TUL0.FUNITID AND TUL0.FLOCALEID = 2052)
                                    INNER JOIN T_BD_STOCK TSK ON(TSK.FMASTERID = TI.FSTOCKID AND(TSK.FUSEORGID = TI.FSTOCKORGID OR EXISTS(SELECT 1 FROM T_META_BASEDATATYPE BT WHERE(BT.FBASEDATATYPEID = 'BD_STOCK' AND BT.FSTRATEGYTYPE = 1))))
                                    LEFT OUTER JOIN T_BD_STOCK_L TSL ON(TSL.FSTOCKID = TI.FSTOCKID AND TSL.FLOCALEID = 2052)
                                    LEFT OUTER JOIN T_BD_UNIT_L TUL1 ON(TI.FBASEUNITID = TUL1.FUNITID AND TUL1.FLOCALEID = 2052)
                                    LEFT OUTER JOIN T_BD_UNIT TUE ON TMS.FAUXUNITID = TUE.FUNITID
                                    LEFT OUTER JOIN T_BD_UNIT_L TUL2 ON(TI.FSECUNITID = TUL2.FUNITID AND TUL2.FLOCALEID = 2052)
                                    LEFT OUTER JOIN V_ITEMCLASS_OWNER VO ON((VO.FMASTERID = TI.FOWNERID AND VO.FFORMID = TI.FOWNERTYPEID) AND(VO.FUSEORGID = TI.FSTOCKORGID OR VO.FUSEORGID = 0 OR EXISTS(SELECT 1 FROM T_META_BASEDATATYPE BT WHERE(BT.FBASEDATATYPEID = VO.FFORMID AND BT.FSTRATEGYTYPE = 1))))
                                    LEFT OUTER JOIN V_ITEMCLASS_OWNER_L VO_L ON(VO.FITEMID = VO_L.FITEMID AND VO_L.FLOCALEID = 2052)
                                    LEFT OUTER JOIN V_ITEMCLASS_KEEPER VK ON((VK.FMASTERID = TI.FKEEPERID AND VK.FFORMID = TI.FKEEPERTYPEID)AND(VK.FUSEORGID = TI.FSTOCKORGID OR VK.FUSEORGID = 0 OR EXISTS(SELECT 1 FROM T_META_BASEDATATYPE BT WHERE(BT.FBASEDATATYPEID = VK.FFORMID AND BT.FSTRATEGYTYPE = 1))))
                                    LEFT OUTER JOIN V_ITEMCLASS_KEEPER_L VK_L ON(VK.FITEMID = VK_L.FITEMID AND VK_L.FLOCALEID = 2052)--以下仓位
                                    LEFT OUTER JOIN T_BAS_FLEXVALUESDETAIL FVD ON TI.FSTOCKLOCID = FVD.FID
                                    LEFT OUTER JOIN T_BAS_FLEXVALUESENTRY_L VFF100001 ON(FVD.FOPCODE = VFF100001.FENTRYID AND VFF100001.FLOCALEID = 2052)
                                    --以下锁库和预留
                                    LEFT OUTER JOIN(SELECT TLKE.FSUPPLYINTERID finventryid, SUM(TLKE.FBASEQTY) fbaselockqty, SUM(TLKE.FSECQTY) fseclockqty FROM T_PLN_RESERVELINKENTRY TLKE INNER JOIN T_PLN_RESERVELINK TLKH ON TLKE.FID = TLKH.FID WHERE(TLKE.FSUPPLYFORMID = 'STK_Inventory' AND TLKE.FLINKTYPE = '4')GROUP BY TLKE.FSUPPLYINTERID) tsub ON TI.FID = TSUB.FINVENTRYID
                                     WHERE 1 = 1 ");
                if (!string.IsNullOrWhiteSpace(FMaterialId))
                {
                    sbSql.AppendLine(" AND  M.FTHIRDBILLNO = @MaterialId ");
                    lstParam.Add(new SqlParam("@MaterialId", KDDbType.String, FMaterialId));
                }
                if (!string.IsNullOrWhiteSpace(FStockId))
                {
                    sbSql.AppendLine(" AND TSK.FTHIRDBILLNO =  @StockId ");
                    lstParam.Add(new SqlParam("@StockId", KDDbType.String, FStockId));
                }
                string VkNumber = "";
                if (!string.IsNullOrWhiteSpace(FVkNumber))
                {
                    VkNumber = CommonService.VKGetBaseDataIdByValue(ctx, FVkNumber);
                    if (VkNumber != "0")
                    {
                        sbSql.AppendLine(" AND TI.FNUMBER = @VkNumber ");
                        lstParam.Add(new SqlParam("@VkNumber", KDDbType.String, VkNumber));
                    }
                }
                sbSql.AppendLine(" ) t ");//WHERE TI.FBASEQTY > 0

                sbSql.AppendFormat("SELECT FIDENTITYID,  FstockOrgId, FstockOrgname, FMaterialId, FMaterialName, FStockId, FStockName, FBaseQty  FROM {0} ", strTempTable);

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();

                    //var Datas = TotalDatas.Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                    //    && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "产品数据数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "产品数据数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "产品数据数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("卡储值积分交易数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 资金对比数据查询
        internal string Capital(Context ctx, int iPageSize, int iPageNum, string FCONTACTUNIT, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();
                IDBService dbSvr = Kingdee.BOS.Contracts.ServiceFactory.GetDBService(ctx);
                string strTempTable = dbSvr.CreateTemporaryTableName(ctx);

                sbSql.AppendLine("SELECT FEndData, FCONTACTUNIT, Kingdee,");
                sbSql.AppendFormat("    ROW_NUMBER() OVER (ORDER BY FCONTACTUNIT, Kingdee DESC) AS FIDENTITYID INTO {0} FROM ", strTempTable).AppendLine();
                sbSql.AppendLine(@"(select (sum(t.FREALRECAMOUNTFOR) + sum(ISNULL(t1.FREALREFUNDAMOUNTFOR,0))) - SUM(ISNULL(FALLAMOUNTFOR,0)) as FEndData,
                             t3.FTHIRDBILLNO  as FCONTACTUNIT,T.FCONTACTUNIT AS Kingdee
                             from  T_AR_RECEIVEBILL t 
                             INNER JOIN T_BD_CUSTOMER T3 ON T3.FCUSTID  = T.FCONTACTUNIT
                            LEFT join (SELECT FCONTACTUNIT,FREALREFUNDAMOUNTFOR
                             FROM T_AR_REFUNDBILL t1)t1 on t1.FCONTACTUNIT = t.FCONTACTUNIT 
                            LEFT JOIN (SELECT  FCUSTOMERID,FALLAMOUNTFOR FROM  t_AR_receivable T2)
                             T2 ON T2.FCUSTOMERID = T.FCONTACTUNIT
                             where 1 = 1 
                            ");
                if (!string.IsNullOrWhiteSpace(FCONTACTUNIT))
                {
                    sbSql.AppendLine(" AND t3.FTHIRDBILLNO = @CONTACTUNIT ");
                    lstParam.Add(new SqlParam("@CONTACTUNIT", KDDbType.String, FCONTACTUNIT));
                }
                sbSql.AppendLine("  group by t.FCONTACTUNIT,t3.FTHIRDBILLNO) t ");//WHERE TI.FBASEQTY > 0
                sbSql.AppendFormat("SELECT FIDENTITYID, FEndData, FCONTACTUNIT, Kingdee  FROM {0} ", strTempTable);
                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));
                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int iBNum = 1;
                    int iENum = 10;
                    int num = 0;
                    int count = TotalDatas.Count;
                    iPageSize = (iPageSize <= 0) ? TotalDatas.Count : iPageSize;
                    num = (int)Math.Ceiling((decimal)(Convert.ToDecimal(count) / iPageSize));
                    iPageNum = (iPageNum <= 0) ? 1 : iPageNum;
                    iBNum = (iPageSize * (iPageNum - 1)) + 1;
                    iENum = iPageSize * iPageNum;

                    JObject Data = new JObject();
                    Data.Add("TotalCount", count);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", num);
                    Data.Add("CurPage", iPageNum);
                    var Datas = TotalDatas.AsEnumerable().Where(p => Convert.ToInt32(p["FIDENTITYID"]) >= iBNum
                        && Convert.ToInt32(p["FIDENTITYID"]) <= iENum).OrderBy(q => q["FIDENTITYID"]).ToList();
                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", JArray.FromObject(Datas));

                        result["Result"] = true;
                        result["Message"] = "资金数据查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "资金数据查询成功，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "资金数据查询成功，返回查询结果为空！";
                }

                dbSvr.DeleteTemporaryTableName(ctx, new string[] { strTempTable });
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("卡储值积分交易数据查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 会员新增注册Old
        internal string RegisterVIPMemberOld(Context ctx, string vipParams, string cardParams, JObject result)
        {
            result["Result"] = false;

            string CardNo = "";       //卡号
            string CardType = "";     //卡类型
            string CardLevel = "";    //卡级别
            string BranchNumber = ""; //门店编码
            string VipName = "";      //会员姓名
            string MobileNo = "";     //手机号
            string Birthday = "";     //生日
            string Sex = "";          //性别
            string CredNo = "";       //证件号
            string Email = "";        //邮箱
            string Weixin = "";       //微信号
            string QQ = "";           //QQ号
            string Tel = "";          //固定电话
            string CredType = "";     //证件类型
            string Nationality = "";  //民族
            long CountryId = 0;       //国别
            long RegionId = 0;        //省份
            long CityId = 0;          //城市
            long CountyId = 0;        //县区
            string Educattion = "";   //学历
            string BusArea = "";      //商圈
            string Community = "";    //社区
            string Source = "";       //来源
            string HomeAddr = "";     //家庭住址
            string WorkAddr = "";     //工作地址
            string RefCardNo = "";    //推荐人卡号号
            string Note = "";         //备注
            string FromId = "CMK_VIP_MembershipInfo"; //表单id

            string Applets_Mode = "";


            try
            {
                JObject jParams = JObject.Parse(vipParams);

                BranchNumber = CommonService.GetJParamString(jParams, "BranchNumber");
                if (string.IsNullOrWhiteSpace(BranchNumber))
                {
                    result["ResCode"] = 301;
                    result["Message"] = "参数【BranchNumber：门店编码】未设置！";
                    return result.ToString();
                }
                long lBranchId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", BranchNumber);
                if (lBranchId == 0)
                {
                    result["ResCode"] = 302;
                    result["Message"] = "参数【BranchNumber：门店编码】在系统中不存在！";
                    return result.ToString();
                }

                MobileNo = CommonService.GetJParamString(jParams, "MobileNo");
                if (string.IsNullOrWhiteSpace(MobileNo))
                {
                    result["ResCode"] = 303;
                    result["Message"] = "参数【MobileNo：手机号】未设置！";
                    return result.ToString();
                }

                string strSql = string.Format("SELECT TOP 1 1 FROM CMK_T_VIP_Member WHERE FMobile = '{0}' ", MobileNo);
                var vipData = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (vipData != null && vipData.Count > 0)
                {
                    result["ResCode"] = 100;
                    result["Message"] = "参数【MobileNo：手机号】已经被注册过，不允许重复注册！";

                    var VIPData = this.ReturnVIPMemberInfo(ctx, "", MobileNo);
                    if (VIPData != null && VIPData.Count > 0)
                    {
                        var jVipDatas = JArray.FromObject(VIPData);
                        if (jVipDatas != null && jVipDatas.Count > 0)
                        {
                            foreach (JObject jVipData in jVipDatas)
                            {
                                var FTimeStamp = "0";
                                if (jVipData["FTimeStamp"] != null)
                                {
                                    FTimeStamp = Convert.ToInt64(CommonService.GetJParamString(jVipData, "FTimeStamp")).ToString("X8");
                                }
                                jVipData["FTimeStamp"] = string.Format("0x{0}", FTimeStamp.PadLeft(16, '0'));
                            }
                        }

                        result["Data"] = jVipDatas;
                    }

                    return result.ToString();
                }

                VipName = CommonService.GetJParamString(jParams, "VipName");
                if (string.IsNullOrWhiteSpace(VipName))
                {
                    VipName = MobileNo;
                }

                DateTime dt;
                Birthday = CommonService.GetJParamString(jParams, "Birthday");
                if (!DateTime.TryParse(Birthday, out dt))
                {
                    Birthday = "1900-01-01";
                }

                CredNo = CommonService.GetJParamString(jParams, "CredNo");
                Email = CommonService.GetJParamString(jParams, "Email");
                Weixin = CommonService.GetJParamString(jParams, "Weixin");
                QQ = CommonService.GetJParamString(jParams, "QQ");
                Tel = CommonService.GetJParamString(jParams, "Tel");

                string strValue = CommonService.GetJParamString(jParams, "Sex");
                Sex = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Sex);

                strValue = CommonService.GetJParamString(jParams, "CredType");
                CredType = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.CredType);
                strValue = CommonService.GetJParamString(jParams, "Nationality");
                Nationality = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Nationality);

                strValue = CommonService.GetJParamString(jParams, "Country");
                CountryId = CommonService.GetAreaDetailIdByValue(ctx, strValue, CommonService.Country);
                strValue = CommonService.GetJParamString(jParams, "Provincial");
                RegionId = CommonService.GetAreaDetailIdByValue(ctx, strValue, CommonService.Region);

                strValue = CommonService.GetJParamString(jParams, "City");
                CityId = CommonService.GetAreaDetailIdByValue(ctx, strValue, CommonService.City);
                strValue = CommonService.GetJParamString(jParams, "County");
                CountyId = CommonService.GetAreaDetailIdByValue(ctx, strValue, CommonService.Country);

                strValue = CommonService.GetJParamString(jParams, "Educattion");
                Educattion = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Educattion);
                strValue = CommonService.GetJParamString(jParams, "BusArea");
                BusArea = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.BusArea);
                strValue = CommonService.GetJParamString(jParams, "Community");
                Community = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Community);
                strValue = CommonService.GetJParamString(jParams, "Source");
                Source = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Source);

                HomeAddr = CommonService.GetJParamString(jParams, "HomeAddr");
                WorkAddr = CommonService.GetJParamString(jParams, "WorkAddr");
                RefCardNo = CommonService.GetJParamString(jParams, "RefCardNo");
                Note = CommonService.GetJParamString(jParams, "Note");
                Applets_Mode = CommonService.GetJParamString(jParams, "AppletsMode");  //小程序模式（001-储值模式 002-山姆模式） 不同模式发卡不一样

                if (string.IsNullOrWhiteSpace(Note))
                {
                    Note = "调用注册新会员接口生成";
                }

                jParams = JObject.Parse(cardParams);

                CardType = CommonService.GetJParamString(jParams, "CardType");
                if (string.IsNullOrWhiteSpace(CardType))
                {
                    result["ResCode"] = 304;
                    result["Message"] = "参数【CardType：卡类型】未设置！";
                    return result.ToString();
                }
                long lCardTypeId = CommonService.GetBaseDataIdByValue(ctx, "CMK_T_VIP_CARDTYPE", "FCardTypeId", "FNumber", CardType);
                if (lCardTypeId == 0)
                {
                    result["ResCode"] = 305;
                    result["Message"] = "参数【CardType：卡类型】在系统中不存在！";
                    return result.ToString();
                }

                long lCardLevelId = 0;
                CardLevel = CommonService.GetJParamString(jParams, "CardLevel");
                if (!string.IsNullOrWhiteSpace(CardLevel))
                {
                    lCardLevelId = CommonService.GetBaseDataIdByValue(ctx, "CMK_T_VIP_CARDLEVEL", "FCardLevelId", "FNumber", CardLevel);
                    if (lCardLevelId == 0)
                    {
                        result["ResCode"] = 306;
                        result["Message"] = "参数【CardLevel：卡级别】在系统中不存在！";
                        return result.ToString();
                    }
                }

                string AutoCardNo = CommonService.GetJParamString(jParams, "AutoCardNo");
                if (AutoCardNo == "Y")
                {
                    CardNo = this.GetAutoCardNo(ctx, BranchNumber, lCardTypeId);
                }
                else
                {
                    CardNo = CommonService.GetJParamString(jParams, "CardNo");
                    if (string.IsNullOrWhiteSpace(CardNo))
                    {
                        CardNo = MobileNo;
                    }
                }

                string strSQL = string.Format("SELECT TOP 1 1 FROM CMK_T_VIP_CARD WHERE FNumber = '{0}' AND FCardStatus <> 'E' ", CardNo);
                var dataCards = DBUtils.ExecuteDynamicObject(ctx, strSQL);
                if (dataCards != null && dataCards.Count > 0)
                {
                    result["ResCode"] = 100;
                    result["Message"] = string.Format("会员卡号【{0}】在系统中已经存在！", CardNo);
                    return result.ToString();
                }

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    strSQL = @"EXEC CMK_LS_CreateNewVIPCard_Appand @UserID, 0, @CardNumber, @CardTypeID, @BranchID, @Note, @VIPName, @VIPSex, @VIPBirthday, 
                        '', @VIPMobile, '', '', '', '', '1', '1', '1', '', '', '', '', '', '', '', '', 0, 0, '', '', '1', '', @IntroduceCardNo, '', @CardLevelId,@FromId";

                    List<SqlParam> lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, ctx.UserId));
                    lstParam.Add(new SqlParam("@CardNumber", KDDbType.String, CardNo));
                    lstParam.Add(new SqlParam("@CardTypeID", KDDbType.Int64, lCardTypeId));
                    lstParam.Add(new SqlParam("@CardLevelId", KDDbType.Int64, lCardLevelId));
                    lstParam.Add(new SqlParam("@BranchID", KDDbType.Int64, lBranchId));
                    lstParam.Add(new SqlParam("@Note", KDDbType.String, Note));
                    lstParam.Add(new SqlParam("@VIPName", KDDbType.String, VipName));
                    lstParam.Add(new SqlParam("@VIPSex", KDDbType.String, Sex));
                    lstParam.Add(new SqlParam("@VIPBirthday", KDDbType.String, Birthday));
                    lstParam.Add(new SqlParam("@VIPMobile", KDDbType.String, MobileNo));
                    lstParam.Add(new SqlParam("@IntroduceCardNo", KDDbType.String, RefCardNo));
                    lstParam.Add(new SqlParam("@FromId", KDDbType.String, FromId));
                    DBUtils.Execute(ctx, strSQL, lstParam);

                    strSQL = @"UPDATE CMK_T_VIP_Member SET FIDNumber = @FIDNumber, FWeixin = @FWeixin, FQQ = @FQQ, FTel = @FTel, FEmail = @FEmail, 
                        FIDType = @CredType, FNationality = @Nationality, FCountryID = @FCountryID, FRegionID = @FRegionID, FCityID = @FCityID, FCountyID = @FCountyID,
                        FEducation = @Educattion, FBusinessArea = @BusArea, FCommunity = @Community, FVIPWhereFrom = @Source,  
                        FFamilyAddress = @HomeAddr, FWorkAddress = @WorkAddr WHERE FMobile = @FMobile ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FIDNumber", KDDbType.String, CredNo));
                    lstParam.Add(new SqlParam("@FWeixin", KDDbType.String, Weixin));
                    lstParam.Add(new SqlParam("@FQQ", KDDbType.String, QQ));
                    lstParam.Add(new SqlParam("@FTel", KDDbType.String, Tel));
                    lstParam.Add(new SqlParam("@FEmail", KDDbType.String, Email));
                    lstParam.Add(new SqlParam("@CredType", KDDbType.String, CredType));
                    lstParam.Add(new SqlParam("@Nationality", KDDbType.String, Nationality));
                    lstParam.Add(new SqlParam("@FCountryID", KDDbType.Int64, CountryId));
                    lstParam.Add(new SqlParam("@FRegionID", KDDbType.Int64, RegionId));
                    lstParam.Add(new SqlParam("@FCityID", KDDbType.Int64, CityId));
                    lstParam.Add(new SqlParam("@FCountyID", KDDbType.Int64, CountyId));
                    lstParam.Add(new SqlParam("@Educattion", KDDbType.String, Educattion));
                    lstParam.Add(new SqlParam("@BusArea", KDDbType.String, BusArea));
                    lstParam.Add(new SqlParam("@Community", KDDbType.String, Community));
                    lstParam.Add(new SqlParam("@Source", KDDbType.String, Source));
                    lstParam.Add(new SqlParam("@HomeAddr", KDDbType.String, HomeAddr));
                    lstParam.Add(new SqlParam("@WorkAddr", KDDbType.String, WorkAddr));
                    lstParam.Add(new SqlParam("@FMobile", KDDbType.String, MobileNo));
                    DBUtils.Execute(ctx, strSQL, lstParam);
                    scope.Complete();
                }

                result["Result"] = true;
                result["ResCode"] = 200;
                result["Message"] = "会员新增注册成功";

                var resData = this.ReturnVIPMemberInfo(ctx, "", MobileNo);
                if (resData != null && resData.Count > 0)
                {
                    var jVipDatas = JArray.FromObject(resData);
                    if (jVipDatas != null && jVipDatas.Count > 0)
                    {
                        foreach (JObject jVipData in jVipDatas)
                        {
                            var FTimeStamp = "0";
                            if (jVipData["FTimeStamp"] != null)
                            {
                                FTimeStamp = Convert.ToInt64(CommonService.GetJParamString(jVipData, "FTimeStamp")).ToString("X8");
                            }
                            jVipData["FTimeStamp"] = string.Format("0x{0}", FTimeStamp.PadLeft(16, '0'));
                        }
                    }

                    result["Data"] = jVipDatas;
                }

                strSql = "SELECT FContent, FSendSms FROM CMK_VIP_MessageTemplateEntry WHERE FTYPE = 'HYZC' ";
                var dataSms = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (dataSms != null && dataSms.Count() > 0)
                {
                    if (Convert.ToString(dataSms.First()["FSendSms"]) == "1")
                    {
                        string strSmsContent = Convert.ToString(dataSms.First()["FContent"]);

                        strSql = string.Format(@"SELECT TOP 1 t2.FName AS FVIPName, t1.FSex, t3.FNumber AS FCardNo, t4.FName AS FCardLevel FROM CMK_T_VIP_Member t1 
                            INNER JOIN CMK_T_VIP_Member_L t2 ON t1.FVIPID = t2.FVIPID AND t2.FLOCALEID = {0}
                            INNER JOIN CMK_T_VIP_CARD t3 ON t3.FVIPMemberID = t1.FVIPID
                            INNER JOIN CMK_T_VIP_CARDLEVEL_L t4 ON t4.FCardLevelId = t3.FCardLevelId AND t4.FLOCALEID = {0}
                                WHERE t1.FMobile = '{1}' ", ctx.UserLocale.LCID, MobileNo);
                        var dataVips = DBUtils.ExecuteDynamicObject(ctx, strSql);
                        if (dataVips != null && dataVips.Count > 0)
                        {
                            var dataVip = dataVips.First();
                            strSmsContent = strSmsContent.Replace("@会员姓名@", Convert.ToString(dataVip["FVIPName"]));
                            strSmsContent = strSmsContent.Replace("@会员称呼@", Convert.ToString(dataVip["FSex"]) == "eb28b65afd62405299f061c9173a81de" ? "先生" : "女士");
                            strSmsContent = strSmsContent.Replace("@会员卡号@", Convert.ToString(dataVip["FCardNo"]));
                            strSmsContent = strSmsContent.Replace("@卡级别@", Convert.ToString(dataVip["FCardLevel"]));
                        }

                        //ESBSmsService smsService = new ESBSmsService();
                        //smsService.SendSmsService(MobileNo, strSmsContent);
                    }
                }
            }
            catch (Exception ex)
            {
                result["ResCode"] = 999;
                result["Result"] = false;
                result["Message"] = string.Format("会员新增注册失败，原因：{0}", ex.Message);
            }
            return result.ToString();
        }
        #endregion

        #region 会员新增注册New
        internal string RegisterVIPMember(Context ctx, string vipParams, string cardParams, JObject result)
        {
            try
            {
                JArray array;
                string str27;
                DateTime time;
                string strSQL = "";
                string str2 = "";
                string str3 = "";
                string jParamString = "";
                string str5 = "";
                string str6 = "";
                string s = "";
                string vIPSex = "";
                string str9 = "";
                string str10 = "";
                string str11 = "";
                string str12 = "";
                string str13 = "";
                string str14 = "";
                string str15 = "";
                long num = 0L;
                long num2 = 0L;
                long num3 = 0L;
                long num4 = 0L;
                string str16 = "";
                string str17 = "";
                string str18 = "";
                string str19 = "";
                string str20 = "";
                string str21 = "";
                string introduceCardNo = "";
                string str23 = "";
                string openID = "";
                result["Result"] = false;
                JObject jParams = JObject.Parse(vipParams);

                //经营模式标识：区分储值模式和山姆模式会员发卡
                string BusinessMode = CommonService.GetJParamString(jParams, "BusinessMode");
                if (string.IsNullOrWhiteSpace(BusinessMode))
                {
                    result["Message"] = ResManager.LoadKDString("参数【BusinessMode：经营模式标识】未设置！", "017178000000462", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }

                string BusinessModeId = CommonService.GetBrandIpByNumber(ctx, BusinessMode);
                if (string.IsNullOrWhiteSpace(BusinessModeId))
                {
                    result["Message"] = ResManager.LoadKDString("参数【BusinessMode：经营模式标识】在系统中不存在！", "017178000000462", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }

                jParamString = CommonService.GetJParamString(jParams, "BranchNumber");
                if (string.IsNullOrWhiteSpace(jParamString))
                {
                    result["Message"] = ResManager.LoadKDString("参数【BranchNumber：门店编码】未设置！", "017178000000462", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                long branchID = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", jParamString, 0L);
                if (branchID == 0L)
                {
                    result["Message"] = ResManager.LoadKDString("参数【BranchNumber：门店编码】在系统中不存在！", "017178000000452", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                str6 = CommonService.GetJParamString(jParams, "MobileNo");
                if (string.IsNullOrWhiteSpace(str6))
                {
                    result["Message"] = ResManager.LoadKDString("参数【MobileNo：手机号】未设置！", "017178000001720", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                if (CommonService.GetJParamString(jParams, "MultCard") != "Y")
                {
                    string str26 = string.Format("SELECT TOP 1 FVIPID FROM CMK_T_VIP_Member WHERE FMobile = '{0}' ", str6);
                    DynamicObjectCollection objects = DBUtils.ExecuteDynamicObject(ctx, str26, null, null, CommandType.Text, new SqlParam[0]);
                    if ((objects != null) && (objects.Count > 0))
                    {
                        result["Code"] = 1;
                        result["ResCode"] = 101;
                        result["Message"] = ResManager.LoadKDString("参数【MobileNo：手机号】已经被注册过，不允许重复注册！", "017178000001721", SubSystemType.RETAIL, new object[0]);
                        DynamicObjectCollection objects2 = this.ReturnVIPMemberInfo(ctx, "", str6);
                        if ((objects2 != null) && (objects2.Count > 0))
                        {
                            array = JArray.FromObject(objects2);
                            if ((array != null) && (array.Count > 0))
                            {
                                foreach (JObject obj3 in (IEnumerable<JToken>)array)
                                {
                                    str27 = "0";
                                    if (obj3["FTimeStamp"] != null)
                                    {
                                        str27 = Convert.ToInt64(CommonService.GetJParamString(obj3, "FTimeStamp")).ToString("X8");
                                    }
                                    obj3["FTimeStamp"] = string.Format("0x{0}", str27.PadLeft(0x10, '0'));
                                }
                            }
                            result["Data"] = array;
                        }
                        return result.ToString();
                    }
                }
                //特殊处理，若名字
                try
                {
                    str5 = CommonService.GetJParamString(jParams, "VipName");  //ho&amp;khbbbn
                    str5 = str5.Replace("&", "").Replace(";", "");
                    if (string.IsNullOrWhiteSpace(str5))
                    {
                        str5 = str6;
                    }
                }
                catch (Exception)
                {
                    str5 = str6;
                }

                s = CommonService.GetJParamString(jParams, "Birthday");
                if (!DateTime.TryParse(s, out time))
                {
                    s = "1900-01-01";
                }
                str9 = CommonService.GetJParamString(jParams, "CredNo");
                str10 = CommonService.GetJParamString(jParams, "Email");
                str11 = CommonService.GetJParamString(jParams, "Weixin");
                str12 = CommonService.GetJParamString(jParams, "QQ");
                str13 = CommonService.GetJParamString(jParams, "Tel");
                string strValue = CommonService.GetJParamString(jParams, "Sex");
                vIPSex = CommonService.GetAuxDataIdByName(ctx, strValue, "8bcd487d7147412b832895578579089f");
                strValue = CommonService.GetJParamString(jParams, "CredType");
                str14 = CommonService.GetAuxDataIdByName(ctx, strValue, "B5BF313F-6FCA-4E9B-BE5A-1C06332B3B82");
                strValue = CommonService.GetJParamString(jParams, "Nationality");
                str15 = CommonService.GetAuxDataIdByName(ctx, strValue, "9ab4ddbb7941472690c407e4343e59d7");
                strValue = CommonService.GetJParamString(jParams, "Country");
                num = CommonService.GetAreaDetailIdByValue(ctx, strValue, "005056944621b40511e3ae740dbf1f1a");
                strValue = CommonService.GetJParamString(jParams, "Provincial");
                num2 = CommonService.GetAreaDetailIdByValue(ctx, strValue, "005056944621b40511e3ae741eea45e3");
                strValue = CommonService.GetJParamString(jParams, "City");
                num3 = CommonService.GetAreaDetailIdByValue(ctx, strValue, "005056944621b40511e3ae743f4229a2");
                strValue = CommonService.GetJParamString(jParams, "County");
                num4 = CommonService.GetAreaDetailIdByValue(ctx, strValue, "005056944621b40511e3ae7448573af3");
                strValue = CommonService.GetJParamString(jParams, "Educattion");
                str16 = CommonService.GetAuxDataIdByName(ctx, strValue, "67e75837258142b8b42dcaeb3190bfce");
                strValue = CommonService.GetJParamString(jParams, "BusArea");
                str17 = CommonService.GetAuxDataIdByName(ctx, strValue, "005056c00008968111e3b1a485b25282");
                strValue = CommonService.GetJParamString(jParams, "Community");
                str18 = CommonService.GetAuxDataIdByName(ctx, strValue, "005056c00008968111e3b1a550db9c1a");
                strValue = CommonService.GetJParamString(jParams, "Source");
                str19 = CommonService.GetAuxDataIdByName(ctx, strValue, "bf6c06b51cc4a13a11e484d345759d8e");
                str20 = CommonService.GetJParamString(jParams, "HomeAddr");
                str21 = CommonService.GetJParamString(jParams, "WorkAddr");
                introduceCardNo = CommonService.GetJParamString(jParams, "RefCardNo");
                str23 = CommonService.GetJParamString(jParams, "Note");
                openID = CommonService.GetJParamString(jParams, "OpenID");
                if (string.IsNullOrWhiteSpace(str23))
                {
                    str23 = ResManager.LoadKDString("调用注册新会员接口生成", "017178000001722", SubSystemType.RETAIL, new object[0]);
                }
                int num6 = 0;
                long cardTypeId = 0L;
                if (CommonService.GetJParamString(jParams, "CreateCard") != "N")
                {
                    num6 = 1;
                    jParams = JObject.Parse(cardParams);
                    str3 = CommonService.GetJParamString(jParams, "CardType");
                    if (string.IsNullOrWhiteSpace(str3))
                    {
                        result["Message"] = ResManager.LoadKDString("参数【CardType：卡类型】未设置！", "017178000001723", SubSystemType.RETAIL, new object[0]);
                        return result.ToString();
                    }
                    cardTypeId = CommonService.GetBaseDataIdByValue(ctx, "CMK_T_VIP_CARDTYPE", "FCardTypeId", "FNumber", str3, 0L);
                    if (cardTypeId == 0L)
                    {
                        result["Message"] = ResManager.LoadKDString("参数【CardType：卡类型】在系统中不存在！", "017178000001724", SubSystemType.RETAIL, new object[0]);
                        return result.ToString();
                    }
                    if (CommonService.GetJParamString(jParams, "AutoCardNo") == "Y")
                    {
                        str2 = this.GetAutoCardNo(ctx, jParamString, cardTypeId);
                    }
                    else
                    {
                        str2 = CommonService.GetJParamString(jParams, "CardNo");
                        if (string.IsNullOrWhiteSpace(str2))
                        {
                            str2 = str6;
                        }
                    }
                    strSQL = string.Format("SELECT TOP 1 FCardID FROM CMK_T_VIP_CARD WHERE FNumber = '{0}' AND FCardStatus <> 'E' ", str2);
                    DynamicObjectCollection objects3 = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                    if ((objects3 != null) && (objects3.Count > 0))
                    {
                        result["Result"] = false;
                        result["Code"] = 1;
                        result["Message"] = string.Format(ResManager.LoadKDString("会员卡号【{0}】在系统中已经存在！", "017178000001725", SubSystemType.RETAIL, new object[0]), str2);
                        return result.ToString();
                    }
                }
                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    string str30 = CMK_Brand_POSVIPCardPublish(ctx, BusinessModeId, str2, cardTypeId, branchID, str23, str5, vIPSex, s, "", str6, "", "", "", "", "1", "1", "1", "", "", "", "", "", "", "", "", 0M, 0L, "", "", "1", "", introduceCardNo, "21218CCA77804D2BA1922C33E0151105", num6.ToString());
                    if (!string.IsNullOrWhiteSpace(str30))
                    {
                        result["Message"] = ResManager.LoadKDString(str30, "017178000001725", SubSystemType.RETAIL, new object[0]);
                        return result.ToString();
                    }
                    List<SqlParam> paramList = new List<SqlParam>();
                    StringBuilder builder = new StringBuilder();
                    paramList = new List<SqlParam>();
                    builder.AppendLine("UPDATE CMK_T_VIP_Member SET FMobile = @FMobile ");
                    if (!string.IsNullOrWhiteSpace(s))
                    {
                        builder.AppendLine(", FBirthday = @FBirthday");
                        paramList.Add(new SqlParam("@FBirthday", KDDbType.String, s));
                    }
                    if (!string.IsNullOrWhiteSpace(vIPSex))
                    {
                        builder.AppendLine(", FSex = @FSex");
                        paramList.Add(new SqlParam("@FSex", KDDbType.String, vIPSex));
                    }
                    if (!string.IsNullOrWhiteSpace(str9))
                    {
                        builder.AppendLine(", FIDNumber = @FIDNumber");
                        paramList.Add(new SqlParam("@FIDNumber", KDDbType.String, str9));
                    }
                    if (!string.IsNullOrWhiteSpace(str10))
                    {
                        builder.AppendLine(", FEmail = @FEmail");
                        paramList.Add(new SqlParam("@FEmail", KDDbType.String, str10));
                    }
                    if (!string.IsNullOrWhiteSpace(str11))
                    {
                        builder.AppendLine(", FWeixin = @FWeixin");
                        paramList.Add(new SqlParam("@FWeixin", KDDbType.String, str11));
                    }
                    if (!string.IsNullOrWhiteSpace(str12))
                    {
                        builder.AppendLine(", FQQ = @FQQ");
                        paramList.Add(new SqlParam("@FQQ", KDDbType.String, str12));
                    }
                    if (!string.IsNullOrWhiteSpace(str13))
                    {
                        builder.AppendLine(", FTel = @FTel");
                        paramList.Add(new SqlParam("@FTel", KDDbType.String, str13));
                    }
                    if (!string.IsNullOrWhiteSpace(str14))
                    {
                        builder.AppendLine(", FIDType = @CredType");
                        paramList.Add(new SqlParam("@CredType", KDDbType.String, str14));
                    }
                    if (!string.IsNullOrWhiteSpace(str15))
                    {
                        builder.AppendLine(", FNationality = @Nationality");
                        paramList.Add(new SqlParam("@Nationality", KDDbType.String, str15));
                    }
                    if (num > 0L)
                    {
                        builder.AppendLine(", FCountryID = @FCountryID");
                        paramList.Add(new SqlParam("@FCountryID", KDDbType.Int64, num));
                    }
                    if (num2 > 0L)
                    {
                        builder.AppendLine(", FRegionID = @FRegionID");
                        paramList.Add(new SqlParam("@FRegionID", KDDbType.Int64, num2));
                    }
                    if (num3 > 0L)
                    {
                        builder.AppendLine(", FCityID = @FCityID");
                        paramList.Add(new SqlParam("@FCityID", KDDbType.Int64, num3));
                    }
                    if (num4 > 0L)
                    {
                        builder.AppendLine(", FCountyID = @FCountyID");
                        paramList.Add(new SqlParam("@FCountyID", KDDbType.Int64, num4));
                    }
                    if (!string.IsNullOrWhiteSpace(str16))
                    {
                        builder.AppendLine(", FEducation = @Educattion");
                        paramList.Add(new SqlParam("@Educattion", KDDbType.String, str16));
                    }
                    if (!string.IsNullOrWhiteSpace(str17))
                    {
                        builder.AppendLine(", FBusinessArea = @BusArea");
                        paramList.Add(new SqlParam("@BusArea", KDDbType.String, str17));
                    }
                    if (!string.IsNullOrWhiteSpace(str18))
                    {
                        builder.AppendLine(", FCommunity = @Community");
                        paramList.Add(new SqlParam("@Community", KDDbType.String, str18));
                    }
                    if (!string.IsNullOrWhiteSpace(str19))
                    {
                        builder.AppendLine(", FVIPWhereFrom = @Source");
                        paramList.Add(new SqlParam("@Source", KDDbType.String, str19));
                    }
                    if (!string.IsNullOrWhiteSpace(str20))
                    {
                        builder.AppendLine(", FFamilyAddress = @HomeAddr");
                        paramList.Add(new SqlParam("@HomeAddr", KDDbType.String, str20));
                    }
                    if (!string.IsNullOrWhiteSpace(str21))
                    {
                        builder.AppendLine(", FWorkAddress = @WorkAddr");
                        paramList.Add(new SqlParam("@WorkAddr", KDDbType.String, str21));
                    }
                    if (!string.IsNullOrWhiteSpace(openID))
                    {
                        builder.AppendLine(", FOPENID = @FOPENID");
                        paramList.Add(new SqlParam("@FOPENID", KDDbType.String, openID));
                    }
                    builder.AppendLine(" WHERE FMobile = @FMobile ");
                    paramList.Add(new SqlParam("@FMobile", KDDbType.String, str6));
                    DBUtils.Execute(ctx, builder.ToString(), paramList);
                    scope.Complete();
                }
                result["Result"] = true;
                result["Code"] = 1;
                result["Message"] = ResManager.LoadKDString("会员新增注册成功", "017178000001726", SubSystemType.RETAIL, new object[0]);
                DynamicObjectCollection o = this.ReturnVIPMemberInfo(ctx, "", str6);
                if ((o != null) && (o.Count > 0))
                {
                    array = JArray.FromObject(o);
                    if ((array != null) && (array.Count > 0))
                    {
                        foreach (JObject obj3 in (IEnumerable<JToken>)array)
                        {
                            str27 = "0";
                            if (obj3["FTimeStamp"] != null)
                            {
                                str27 = Convert.ToInt64(CommonService.GetJParamString(obj3, "FTimeStamp")).ToString("X8");
                            }
                            obj3["FTimeStamp"] = string.Format("0x{0}", str27.PadLeft(0x10, '0'));
                        }
                    }
                    result["Data"] = array;
                }
            }
            catch (Exception exception)
            {
                result["Result"] = 0;
                result["Code"] = 1;
                result["Message"] = string.Format(ResManager.LoadKDString("会员新增注册失败，原因：{0}", "017178000001727", SubSystemType.RETAIL, new object[0]), exception.Message);
            }
            return result.ToString();
        }
        #endregion

        #region 自动生成卡号（前缀88 + 门店编码后三位 + 流水号）
        private string GetAutoCardNo(Context ctx, string branchNumber, long cardTypeId)
        {
            string CardNo = "";
            string strPre = "";
            string MaxCardNo = "";
            int MaxCardNum = 1;
            int CardNoLen = 10;
            string strSql = string.Format("SELECT FCardNoLength FROM CMK_T_VIP_CARDTYPE WHERE FCardTypeID = {0} ", cardTypeId);
            var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                CardNoLen = Convert.ToInt32(Datas.First()["FCardNoLength"]);
                if (CardNoLen < 10)
                {
                    CardNoLen = 10;
                }
            }

            if (!string.IsNullOrWhiteSpace(branchNumber))
            {
                int num = 0;
                for (int i = branchNumber.Length; i > branchNumber.Length - 3 && i > 0; i--)
                {
                    string str = branchNumber.Substring(i - 1, 1);
                    int.TryParse(str, out num);
                    strPre = string.Format("{0}{1}", num, strPre);
                    if (strPre.Length >= 3)
                    {
                        break;
                    }
                }
            }

            strPre = string.Format("88{0}", strPre);

            strSql = string.Format("SELECT ISNULL(MAX(FNumber), '0') AS FMaxCardNo FROM CMK_T_VIP_CARD WHERE FNumber LIKE '{0}%' ", strPre);
            Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Count > 0)
            {
                MaxCardNo = Convert.ToString(Datas.First()["FMaxCardNo"]);
                if (MaxCardNo.Length > strPre.Length)
                {
                    MaxCardNo = MaxCardNo.Substring(strPre.Length);
                }
                int.TryParse(MaxCardNo, out MaxCardNum);
                MaxCardNum = MaxCardNum + 1;
            }

            CardNo = string.Format("{0}{1}", strPre, MaxCardNum.ToString().PadLeft(CardNoLen - strPre.Length, '0'));

            return CardNo;
        }
        #endregion

        #region 会员信息修改
        internal string ModifyVIPMemberInfo(Context ctx, string vipParams, bool bUpdateAll, JObject result)
        {
            try
            {
                string BranchNumber = ""; //门店编码
                string VipNumber = "";    //会员编码
                string VipName = "";      //会员姓名
                //string MobileNo = "";     //手机号
                string Birthday = "";     //生日
                string Sex = "";          //性别
                string CredNo = "";       //证件号
                string Email = "";        //邮箱
                string Weixin = "";       //微信号
                string QQ = "";           //QQ号
                string Tel = "";          //固定电话
                string CredType = "";     //证件类型
                string Nationality = "";  //民族
                long CountryId = 0;           //国别
                long RegionId = 0;            //省份
                long CityId = 0;              //城市
                long CountyId = 0;            //县区
                string Educattion = "";   //学历
                string BusArea = "";      //商圈
                string Community = "";    //社区
                string Source = "";       //来源
                string HomeAddr = "";     //家庭住址
                string WorkAddr = "";     //工作地址

                result["Result"] = false;
                JObject jParams = JObject.Parse(vipParams);

                long lVipId = 0;
                VipNumber = CommonService.GetJParamString(jParams, "VipNumber");
                if (string.IsNullOrWhiteSpace(VipNumber))
                {
                    result["Message"] = "参数【VipNumber：会员编号】未设置！";
                    return result.ToString();
                }
                lVipId = CommonService.GetBaseDataIdByValue(ctx, "CMK_T_VIP_Member", "FVIPID", "FNumber", VipNumber);
                if (lVipId == 0)
                {
                    result["Message"] = "参数【VipNumber：会员编号】在系统中不存在！";
                    return result.ToString();
                }

                long lBranchId = 0;
                BranchNumber = CommonService.GetJParamString(jParams, "BranchNumber");
                if (!string.IsNullOrWhiteSpace(BranchNumber))
                {
                    lBranchId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", BranchNumber);
                    if (lBranchId == 0)
                    {
                        result["Message"] = "参数【BranchNumber：门店编码】在系统中不存在！";
                        return result.ToString();
                    }
                }

                VipName = CommonService.GetJParamString(jParams, "VipName");
                //MobileNo = CommonService.GetJParamString(jParams, "MobileNo");

                DateTime dt;
                Birthday = CommonService.GetJParamString(jParams, "Birthday");
                if (!string.IsNullOrWhiteSpace(Birthday) && !DateTime.TryParse(Birthday, out dt))
                {
                    result["Message"] = "参数【Birthday：生日】不是有效的日期！";
                    return result.ToString();
                }

                CredNo = CommonService.GetJParamString(jParams, "CredNo");
                Email = CommonService.GetJParamString(jParams, "Email");
                Weixin = CommonService.GetJParamString(jParams, "Weixin");
                QQ = CommonService.GetJParamString(jParams, "QQ");
                Tel = CommonService.GetJParamString(jParams, "Tel");

                string strValue = CommonService.GetJParamString(jParams, "Sex");
                Sex = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Sex);

                strValue = CommonService.GetJParamString(jParams, "CredType");
                CredType = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.CredType);
                strValue = CommonService.GetJParamString(jParams, "Nationality");
                Nationality = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Nationality);

                strValue = CommonService.GetJParamString(jParams, "Country");
                CountryId = CommonService.GetAreaDetailIdByValue(ctx, strValue, CommonService.Country);
                strValue = CommonService.GetJParamString(jParams, "Provincial");
                RegionId = CommonService.GetAreaDetailIdByValue(ctx, strValue, CommonService.Region);
                strValue = CommonService.GetJParamString(jParams, "City");
                CityId = CommonService.GetAreaDetailIdByValue(ctx, strValue, CommonService.City);
                strValue = CommonService.GetJParamString(jParams, "County");
                CountyId = CommonService.GetAreaDetailIdByValue(ctx, strValue, CommonService.Country);

                strValue = CommonService.GetJParamString(jParams, "Educattion");
                Educattion = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Educattion);
                strValue = CommonService.GetJParamString(jParams, "BusArea");
                BusArea = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.BusArea);
                strValue = CommonService.GetJParamString(jParams, "Community");
                Community = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Community);
                strValue = CommonService.GetJParamString(jParams, "Source");
                Source = CommonService.GetAuxDataIdByName(ctx, strValue, CommonService.Source);

                HomeAddr = CommonService.GetJParamString(jParams, "HomeAddr");
                WorkAddr = CommonService.GetJParamString(jParams, "WorkAddr");

                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();

                sbSql.AppendLine("UPDATE CMK_T_VIP_Member SET FNumber = @FNumber ");

                //if (bUpdateAll || lBranchId > 0)
                //{
                //    sbSql.AppendLine(", FBranchID = @FBranchID");
                //    lstParam.Add(new SqlParam("@FBranchID", KDDbType.Int64, lBranchId));
                //}

                if (!string.IsNullOrWhiteSpace(Birthday))
                {
                    string strSql = string.Format(@"SELECT TOP 1 1 FROM CMK_T_VIP_Member WHERE FNumber = '{0}' 
                        AND FBirthday IS NOT NULL AND FBirthday <> '1900-01-01' AND FBirthday <> '{1}' ", VipNumber, Birthday);
                    var vipData = DBUtils.ExecuteDynamicObject(ctx, strSql);
                    if (vipData != null && vipData.Count > 0)
                    {
                        result.Add("生日", "会员生日已经设置过，不允许修改！");
                    }
                    else
                    {
                        sbSql.AppendLine(", FBirthday = @FBirthday");
                        lstParam.Add(new SqlParam("@FBirthday", KDDbType.String, Birthday));
                    }
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(Sex))
                {
                    sbSql.AppendLine(", FSex = @FSex");
                    lstParam.Add(new SqlParam("@FSex", KDDbType.String, Sex));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(CredNo))
                {
                    sbSql.AppendLine(", FIDNumber = @FIDNumber");
                    lstParam.Add(new SqlParam("@FIDNumber", KDDbType.String, CredNo));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(Email))
                {
                    sbSql.AppendLine(", FEmail = @FEmail");
                    lstParam.Add(new SqlParam("@FEmail", KDDbType.String, Email));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(Weixin))
                {
                    sbSql.AppendLine(", FWeixin = @FWeixin");
                    lstParam.Add(new SqlParam("@FWeixin", KDDbType.String, Weixin));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(QQ))
                {
                    sbSql.AppendLine(", FQQ = @FQQ");
                    lstParam.Add(new SqlParam("@FQQ", KDDbType.String, QQ));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(Tel))
                {
                    sbSql.AppendLine(", FTel = @FTel");
                    lstParam.Add(new SqlParam("@FTel", KDDbType.String, Tel));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(CredType))
                {
                    sbSql.AppendLine(", FIDType = @CredType");
                    lstParam.Add(new SqlParam("@CredType", KDDbType.String, CredType));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(Nationality))
                {
                    sbSql.AppendLine(", FNationality = @Nationality");
                    lstParam.Add(new SqlParam("@Nationality", KDDbType.String, Nationality));
                }

                if (bUpdateAll || CountryId > 0)
                {
                    sbSql.AppendLine(", FCountryID = @FCountryID");
                    lstParam.Add(new SqlParam("@FCountryID", KDDbType.Int64, CountryId));
                }

                if (bUpdateAll || RegionId > 0)
                {
                    sbSql.AppendLine(", FRegionID = @FRegionID");
                    lstParam.Add(new SqlParam("@FRegionID", KDDbType.Int64, RegionId));
                }

                if (bUpdateAll || CityId > 0)
                {
                    sbSql.AppendLine(", FCityID = @FCityID");
                    lstParam.Add(new SqlParam("@FCityID", KDDbType.Int64, CityId));
                }

                if (bUpdateAll || CountyId > 0)
                {
                    sbSql.AppendLine(", FCountyID = @FCountyID");
                    lstParam.Add(new SqlParam("@FCountyID", KDDbType.Int64, CountyId));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(Educattion))
                {
                    sbSql.AppendLine(", FEducation = @Educattion");
                    lstParam.Add(new SqlParam("@Educattion", KDDbType.String, Educattion));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(BusArea))
                {
                    sbSql.AppendLine(", FBusinessArea = @BusArea");
                    lstParam.Add(new SqlParam("@BusArea", KDDbType.String, BusArea));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(Community))
                {
                    sbSql.AppendLine(", FCommunity = @Community");
                    lstParam.Add(new SqlParam("@Community", KDDbType.String, Community));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(Source))
                {
                    sbSql.AppendLine(", FVIPWhereFrom = @Source");
                    lstParam.Add(new SqlParam("@Source", KDDbType.String, Source));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(HomeAddr))
                {
                    sbSql.AppendLine(", FFamilyAddress = @HomeAddr");
                    lstParam.Add(new SqlParam("@HomeAddr", KDDbType.String, HomeAddr));
                }

                if (bUpdateAll || !string.IsNullOrWhiteSpace(WorkAddr))
                {
                    sbSql.AppendLine(", FWorkAddress = @WorkAddr");
                    lstParam.Add(new SqlParam("@WorkAddr", KDDbType.String, WorkAddr));
                }

                sbSql.AppendLine(" WHERE FNumber = @FNumber ");
                lstParam.Add(new SqlParam("@FNumber", KDDbType.String, VipNumber));

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    DBUtils.Execute(ctx, sbSql.ToString(), lstParam);

                    if (!string.IsNullOrWhiteSpace(VipName))
                    {
                        sbSql.Clear();
                        lstParam = new List<SqlParam>();

                        sbSql.AppendLine("UPDATE CMK_T_VIP_Member_L SET FName = @FName WHERE FVIPID IN (SELECT TOP 1 FVIPID FROM CMK_T_VIP_Member WHERE FNumber = @FNumber) ");
                        lstParam.Add(new SqlParam("@FName", KDDbType.String, VipName));
                        lstParam.Add(new SqlParam("@FNumber", KDDbType.String, VipNumber));

                        DBUtils.Execute(ctx, sbSql.ToString(), lstParam);
                    }

                    scope.Complete();
                }

                result["Result"] = true;
                result["Message"] = "会员信息修改成功";

                var resData = this.ReturnVIPMemberInfo(ctx, VipNumber, "");
                if (resData != null && resData.Count > 0)
                {
                    var jVipDatas = JArray.FromObject(resData);
                    if (jVipDatas != null && jVipDatas.Count > 0)
                    {
                        foreach (JObject jVipData in jVipDatas)
                        {
                            var FTimeStamp = "0";
                            if (jVipData["FTimeStamp"] != null)
                            {
                                FTimeStamp = Convert.ToInt64(CommonService.GetJParamString(jVipData, "FTimeStamp")).ToString("X8");
                            }
                            jVipData["FTimeStamp"] = string.Format("0x{0}", FTimeStamp.PadLeft(16, '0'));
                        }
                    }

                    result["Data"] = jVipDatas;
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("会员信息修改失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }

        private DynamicObjectCollection ReturnVIPMemberInfo(Context ctx, string VIPNumber, string MobileNo)
        {
            StringBuilder sbSql = new StringBuilder();
            List<SqlParam> lstParam = new List<SqlParam>();

            sbSql.AppendLine("SELECT FCreateDate, FVIPBranch, FVIPId, FNumber, FName, FSex, FBirthday, FIDType, FIDNumber, FTel, FMobile, FWeixin, FQQ, FEmail, FSource, ");
            sbSql.AppendLine("    FNation, FCountry, FProvince, FCity, FCounty, FEducation, FBusinessArea, FCommunity, FConsumeCount, FConsumeAmount, FReturnCount, FReturnAmount, ");
            sbSql.AppendLine("    FCardId, FCardNo, FCardBranch, FCardType, FCardLevelNumber, FCardLevelName, FCardStatus, FFreezeStatus, FTimeStamp FROM ");
            sbSql.AppendLine("(SELECT TOP 1 TO_CHAR(t1.FCreateDate, 'yyyy-MM-dd') AS FCreateDate, ISNULL(t4.FName, '') AS FVIPBranch, t1.FVIPId, t1.FNumber, t2.FName, ISNULL(t11.FDataValue, '') AS FSex, TO_CHAR(t1.FBirthday, 'yyyy-MM-dd') AS FBirthday, ");
            sbSql.AppendLine("    ISNULL(t8.FDataValue, '') AS FIDType, t1.FIDNumber, t1.FTel, t1.FMobile, t1.FWeixin, t1.FQQ, t1.FEmail, ISNULL(t17.FDataValue, '') AS FSource, ");
            sbSql.AppendLine("    ISNULL(t10.FDataValue, '') AS FNation, ISNULL(t21.FDataValue, '') AS FCountry, ISNULL(t22.FDataValue, '') AS FProvince, ISNULL(t23.FDataValue, '') AS FCity, ISNULL(t24.FDataValue, '') AS FCounty, ");
            sbSql.AppendLine("    ISNULL(t14.FDataValue, '') AS FEducation, ISNULL(t15.FDataValue, '') AS FBusinessArea, ISNULL(t16.FDataValue, '') AS FCommunity, ");
            sbSql.AppendLine("    t1.FConsumeCount, t1.FConsumeAmount, t1.FReturnCount, t1.FReturnAmount, ");
            sbSql.AppendLine("    t3.FCardId, ISNULL(t3.FNumber, '') AS FCardNo, ISNULL(t5.FName, '') AS FCardBranch, ISNULL(t6.FName, '') AS FCardType, ISNULL(t7.FNumber, '') AS FCardLevelNumber, ISNULL(t7_l.FName, '') AS FCardLevelName, ");
            sbSql.AppendLine("    CASE t3.FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus, ");
            sbSql.AppendLine("    CASE t3.FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus, ISNULL(CONVERT(INT, CASE WHEN t1.FTimeStamp > t3.FTimeStamp THEN t1.FTimeStamp ELSE t3.FTimeStamp END), 0) AS FTimeStamp  ");
            sbSql.AppendLine("FROM CMK_T_VIP_Member t1 INNER JOIN CMK_T_VIP_Member_L t2 ON t1.FVIPID = t2.FVIPID AND t2.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARD t3 ON t3.FVIPMemberID = t1.FVIPID ");
            sbSql.AppendLine("    LEFT JOIN CMK_LS_Branch_L t4 ON t4.FID = t1.FBranchID AND t4.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN CMK_LS_Branch_L t5 ON t5.FID = t1.FBranchID AND t5.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARDTYPE_L t6 ON t6.FCardTypeID = t3.FCardTypeID AND t6.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARDLEVEL t7 ON t7.FCardLevelID = t3.FCardLevelID ");
            sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARDLEVEL_L t7_l ON t7_l.FCardLevelID = t3.FCardLevelID AND t7_l.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t8 ON t1.FIDType = t8.FEntryID AND t8.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t10 ON t1.FNationality = t10.FEntryID AND t10.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t11 ON t1.FSex = t11.FEntryID AND t11.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t14 ON t1.FEducation = t14.FEntryID AND t14.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t15 ON t1.FBusinessArea = t15.FEntryID AND t15.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t16 ON t1.FCommunity = t16.FEntryID AND t16.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_BAS_ASSISTANTDATAENTRY_L t17 ON t1.FVIPWhereFrom = t17.FEntryID AND t17.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_ECC_LOGISTICSAREADETAIL_L t21 ON t1.FCountryID = t21.FDetailId AND t21.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_ECC_LOGISTICSAREADETAIL_L t22 ON t1.FRegionID = t22.FDetailId AND t22.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_ECC_LOGISTICSAREADETAIL_L t23 ON t1.FCityID = t23.FDetailId AND t23.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("    LEFT JOIN T_ECC_LOGISTICSAREADETAIL_L t24 ON t1.FCountyID = t24.FDetailId AND t24.FLocaleId = @FLocaleId ");
            sbSql.AppendLine("WHERE 1 = 1 ");

            if (!string.IsNullOrWhiteSpace(VIPNumber))
            {
                sbSql.AppendLine(" AND t1.FNumber = @VIPNumber ");
                lstParam.Add(new SqlParam("@VIPNumber", KDDbType.String, VIPNumber));
            }

            if (!string.IsNullOrWhiteSpace(MobileNo))
            {
                sbSql.AppendLine(" AND t1.FMobile = @MobileNo ");
                lstParam.Add(new SqlParam("@MobileNo", KDDbType.String, MobileNo));
            }
            sbSql.AppendLine(") t ");

            lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, ctx.UserLocale.LCID));

            var Datas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());

            return Datas;
        }
        #endregion

        #region 卡密码修改
        internal string ModifyCardPassWord(Context ctx, string CardNo, string OldPassWord, string NewPassWord, bool bResetPassWord, JObject result)
        {
            try
            {
                result["Result"] = false;
                ITimeService timeSvr = Kingdee.BOS.Contracts.ServiceFactory.GetTimeService(ctx);
                var curDate = timeSvr.GetSystemDateTime(ctx);

                string strSql = string.Format(@"SELECT TOP 1 FCardId, FConsumByPWD, FConsumePassword, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus, 
                        CASE FCardStatus WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus 
                    FROM CMK_T_VIP_CARD WHERE FNumber = '{0}' ", CardNo);
                var cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (cardDatas == null || cardDatas.Count == 0)
                {
                    result["Message"] = "当前卡在系统中不存在，不允许修改卡密码！";
                    return result.ToString();
                }

                var cardData = cardDatas.First();

                if (Convert.ToString(cardData["FConsumByPWD"]) != "1")
                {
                    result["Message"] = "当前卡未设置凭密码消费，不允许修改卡密码！";
                    return result.ToString();
                }

                if (Convert.ToString(cardData["FCardStatus"]) != "正常")
                {
                    result["Message"] = string.Format("当前卡状态为【{0}】，不允许修改卡密码！", Convert.ToString(cardData["FCardStatus"]));
                    return result.ToString();
                }

                string FOperType = bResetPassWord ? "12" : "13";
                long lCardId = Convert.ToInt64(cardData["FCardId"]);

                string strOrgPWD = Convert.ToString(cardData["FConsumePassword"]);
                string strOldPWD = FormsAuthentication.HashPasswordForStoringInConfigFile(Convert.ToString(OldPassWord), "MD5");
                string strNewPWD = FormsAuthentication.HashPasswordForStoringInConfigFile(Convert.ToString(NewPassWord), "MD5");
                if (!strOldPWD.Equals(strOrgPWD) && !bResetPassWord)
                {
                    result["Message"] = string.Format("原密码验证错误，不允许修改卡密码！", Convert.ToString(cardData["FCardStatus"]));
                    return result.ToString();
                }

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    string strSQL = "";
                    List<SqlParam> lstParam = new List<SqlParam>();

                    strSQL = "UPDATE CMK_T_VIP_CARD SET FConsumePassword = @FPassWord WHERE FCardId = @FCardId ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@FPassWord", KDDbType.String, strNewPWD));

                    DBUtils.Execute(ctx, strSQL, lstParam);

                    //写卡流水
                    strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count = 1 ";
                    var Ids = DBUtils.ExecuteDynamicObject(ctx, strSql);

                    strSQL = @"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT @FID, 'CMK_VIP_CardActionFlow', 0, '', '', @OrgID, FBranchID, FCardID, FVIPMEMBERID, 0, 0, 0, 0, 
			                    @Date, @Date, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', @OperType, @UserID, 0, N'调用卡密码修改接口生成', N''  
		                    FROM CMK_T_VIP_CARD WHERE FCardID = @FCardID ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FID", KDDbType.Int64, Ids.First()[0]));
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@OrgID", KDDbType.Int64, ctx.CurrentOrganizationInfo.ID));
                    lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, ctx.UserId));
                    lstParam.Add(new SqlParam("@OperType", KDDbType.String, FOperType));
                    lstParam.Add(new SqlParam("@Date", KDDbType.DateTime, curDate));

                    DBUtils.Execute(ctx, strSQL, lstParam);

                    scope.Complete();
                }

                result["Result"] = true;
                result["Message"] = "卡密码修改成功";
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("卡密码修改失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 卡挂失解挂冻结解冻
        internal string ModifyCardStatus(Context ctx, string CardNo, string bizType, JObject result)
        {
            result["Result"] = false;
            string strOperType = "挂失";

            switch (bizType)
            {
                case "16":
                    strOperType = "挂失";
                    break;
                case "17":
                    strOperType = "解挂";
                    break;
                case "14":
                    strOperType = "冻结";
                    break;
                case "15":
                    strOperType = "解冻";
                    break;
            }

            try
            {
                ITimeService timeSvr = Kingdee.BOS.Contracts.ServiceFactory.GetTimeService(ctx);
                var curDate = timeSvr.GetSystemDateTime(ctx);

                string strSql = string.Format(@"SELECT TOP 1 FCardId, FConsumByPWD, FConsumePassword, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus, 
                        CASE FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus 
                    FROM CMK_T_VIP_CARD WHERE FNumber = '{0}' ", CardNo);
                var cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (cardDatas == null || cardDatas.Count == 0)
                {
                    result["Message"] = string.Format("当前卡在系统中不存在，不允许{0}！", strOperType);
                    return result.ToString();
                }

                var cardData = cardDatas.First();
                long lCardId = Convert.ToInt64(cardData["FCardId"]);

                if (Convert.ToString(cardData["FCardStatus"]) != "正常" && bizType != "17")
                {
                    result["Message"] = string.Format("当前卡状态为【{0}】，不允许{1}！", Convert.ToString(cardData["FCardStatus"]), strOperType);
                    return result.ToString();
                }

                if (Convert.ToString(cardData["FCardStatus"]) != "挂失" && bizType == "17")
                {
                    result["Message"] = string.Format("当前卡状态为【{0}】，不允许{1}！", Convert.ToString(cardData["FCardStatus"]), strOperType);
                    return result.ToString();
                }

                if (Convert.ToString(cardData["FFreezeStatus"]) == "冻结" && bizType == "14")
                {
                    result["Message"] = "当前为冻结状态，不允许冻结！";
                    return result.ToString();
                }

                if (Convert.ToString(cardData["FFreezeStatus"]) != "冻结" && bizType == "15")
                {
                    result["Message"] = "当前为非冻结状态，不允许解冻！";
                    return result.ToString();
                }

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    string strSQL = "";
                    List<SqlParam> lstParam = new List<SqlParam>();

                    switch (bizType)
                    {
                        case "16":
                            strSQL = "UPDATE CMK_T_VIP_CARD SET FCardStatus = 'G' WHERE FCardId = @FCardId ";
                            break;
                        case "17":
                            strSQL = "UPDATE CMK_T_VIP_CARD SET FCardStatus = 'A' WHERE FCardId = @FCardId ";
                            break;
                        case "14":
                            strSQL = "UPDATE CMK_T_VIP_CARD SET FFreezeStatus = 'B' WHERE FCardId = @FCardId ";
                            break;
                        case "15":
                            strSQL = "UPDATE CMK_T_VIP_CARD SET FFreezeStatus = 'A' WHERE FCardId = @FCardId ";
                            break;
                    }

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    DBUtils.Execute(ctx, strSQL, lstParam);

                    //写卡流水
                    strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count = 1 ";
                    var Ids = DBUtils.ExecuteDynamicObject(ctx, strSql);

                    strSQL = @"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT @FID, 'CMK_VIP_CardActionFlow', 0, '', '', @OrgID, FBranchID, FCardID, FVIPMEMBERID, 0, 0, 0, 0, 
			                    @Date, @Date, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', @OperType, @UserID, 0, N'调用卡挂失解挂冻结解冻接口生成', N''  
		                    FROM CMK_T_VIP_CARD WHERE FCardID = @FCardID ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FID", KDDbType.Int64, Ids.First()[0]));
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@OrgID", KDDbType.Int64, ctx.CurrentOrganizationInfo.ID));
                    lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, ctx.UserId));
                    lstParam.Add(new SqlParam("@OperType", KDDbType.String, bizType));
                    lstParam.Add(new SqlParam("@Date", KDDbType.DateTime, curDate));
                    DBUtils.Execute(ctx, strSQL, lstParam);

                    scope.Complete();
                }

                result["Result"] = true;
                result["Message"] = string.Format("卡{0}成功", strOperType);
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("卡{0}失败，原因：{1}", strOperType, ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 卡级别调整
        internal string ModifyCardLevel(Context ctx, string CardNo, string cardLevel, JObject result)
        {
            try
            {
                result["Result"] = false;
                ITimeService timeSvr = Kingdee.BOS.Contracts.ServiceFactory.GetTimeService(ctx);
                var curDate = timeSvr.GetSystemDateTime(ctx);

                string strSql = string.Format(@"SELECT TOP 1 FCardId, FConsumByPWD, FConsumePassword, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus, 
                        CASE FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus 
                    FROM CMK_T_VIP_CARD WHERE FNumber = '{0}' ", CardNo);
                //var cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                //if (cardDatas == null || cardDatas.Count == 0)
                //{
                //    result["Message"] = "当前卡在系统中不存在，不允许调整卡级别！";
                //    return result.ToString();
                //}

                var cardDatas = XDDDBUtils.ExecuteDateSet(strSql);
                if (cardDatas.Tables == null || cardDatas.Tables[0].Rows.Count == 0)
                {
                    result["Message"] = "当前卡在系统中不存在，不允许调整卡级别！";
                    return result.ToString();
                }
                var cardData = cardDatas.Tables[0].Rows[0];
                long lCardId = Convert.ToInt64(cardData["FCardId"]);
                if (Convert.ToString(cardData["FCardStatus"]) != "正常")
                {
                    result["Message"] = string.Format("当前卡状态为【{0}】，不允许调整卡级别！", Convert.ToString(cardData["FCardStatus"]));
                    return result.ToString();
                }
                if (Convert.ToString(cardData["FFreezeStatus"]) != "正常")
                {
                    result["Message"] = "当前卡已冻结，不允许调整卡级别！";
                    return result.ToString();
                }

                long lCardLevelId = CommonService.GetBaseDataIdByValue(ctx, "CMK_T_VIP_CardLevel", "FCardLevelID", "FNumber", cardLevel);
                if (lCardLevelId == 0)
                {
                    result["Message"] = "参数【cardLevel：卡级别编码】在系统中不存在！";
                    return result.ToString();
                }

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    string strSQL = "";
                    List<SqlParam> lstParam = new List<SqlParam>();

                    strSQL = "UPDATE CMK_T_VIP_CARD SET FCardLevelID = @FCardLevelID WHERE FCardId = @FCardId ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@FCardLevelID", KDDbType.Int64, lCardLevelId));

                    //DBUtils.Execute(ctx, strSQL, lstParam);
                    XDDDBUtils.Execute(strSQL, lstParam);

                    StringBuilder sbSql = new StringBuilder();

                    //更新积分批次余额表升级状态
                    sbSql.AppendFormat("UPDATE CMK_t_LotBalance SET FLevelState = -2, FUpdateTime = GETDATE()  WHERE FACCOUNTNAME = 1 AND FLevelState = 0 AND FMEMBERCARD = {0} ", lCardId).AppendLine();

                    //清除积分统计
                    sbSql.AppendFormat(@"UPDATE t1 SET t1.FESPoint = 0, t1.FESValue = 0, t1.FSGPoint = 0, t1.FSGValue = 0, t1.FGBPoint = 0, t1.FGBValue = 0  
                            FROM CMK_XH_VIPCardLevelEntry t1 INNER JOIN CMK_T_VIP_CARD t2 ON t1.FCardId = t2.FCardId  
	                    INNER JOIN CMK_T_VIP_CardLevel t3  ON t2.FCardLevelId = t3.FCardLevelId WHERE t1.FCardId = {0} AND t3.FNUMBER = '01' ", lCardId).AppendLine();
                    sbSql.AppendFormat(@"UPDATE t1 SET t1.FSGPoint = 0, t1.FSGValue = 0, t1.FGBPoint = 0, t1.FGBValue = 0  
                            FROM CMK_XH_VIPCardLevelEntry t1 INNER JOIN CMK_T_VIP_CARD t2 ON t1.FCardId = t2.FCardId  
	                    INNER JOIN CMK_T_VIP_CardLevel t3  ON t2.FCardLevelId = t3.FCardLevelId WHERE t1.FCardId = {0} AND t3.FNUMBER = '02' ", lCardId).AppendLine();
                    sbSql.AppendFormat(@"UPDATE t1 SET t1.FGBPoint = 0, t1.FGBValue = 0 
                            FROM CMK_XH_VIPCardLevelEntry t1 INNER JOIN CMK_T_VIP_CARD t2 ON t1.FCardId = t2.FCardId  
	                    INNER JOIN CMK_T_VIP_CardLevel t3  ON t2.FCardLevelId = t3.FCardLevelId WHERE t1.FCardId = {0} AND t3.FNUMBER = '03' ", lCardId).AppendLine();

                    sbSql.AppendFormat(@"UPDATE t1 SET t1.FSumESPoint = 0, t1.FSumESValue = 0, t1.FSumSGPoint = 0, t1.FSumSGValue = 0, t1.FSumGBPoint = 0, t1.FSumGBValue = 0   
                            FROM CMK_XH_VIPCardLevel t1 INNER JOIN CMK_T_VIP_CARD t2 ON t1.FCardId = t2.FCardId  
	                    INNER JOIN CMK_T_VIP_CardLevel t3  ON t2.FCardLevelId = t3.FCardLevelId WHERE t1.FCardId = {0} AND t3.FNUMBER = '01' ", lCardId).AppendLine();
                    sbSql.AppendFormat(@"UPDATE t1 SET t1.FSumSGPoint = 0, t1.FSumSGValue = 0, t1.FSumGBPoint = 0, t1.FSumGBValue = 0  
                            FROM CMK_XH_VIPCardLevel t1 INNER JOIN CMK_T_VIP_CARD t2 ON t1.FCardId = t2.FCardId  
	                    INNER JOIN CMK_T_VIP_CardLevel t3  ON t2.FCardLevelId = t3.FCardLevelId WHERE t1.FCardId = {0} AND t3.FNUMBER = '02' ", lCardId).AppendLine();
                    sbSql.AppendFormat(@"UPDATE t1 SET t1.FSumGBPoint = 0, t1.FSumGBValue = 0 
                            FROM CMK_XH_VIPCardLevel t1 INNER JOIN CMK_T_VIP_CARD t2 ON t1.FCardId = t2.FCardId  
	                    INNER JOIN CMK_T_VIP_CardLevel t3  ON t2.FCardLevelId = t3.FCardLevelId WHERE t1.FCardId = {0} AND t3.FNUMBER = '03' ", lCardId).AppendLine();

                    //DBUtils.Execute(ctx, string.Format("/*dialect*/ {0}", sbSql.ToString()));
                    XDDDBUtils.Execute(string.Format("/*dialect*/ {0}", sbSql.ToString()));

                    //写卡流水
                    strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count = 1 ";
                    //var Ids = DBUtils.ExecuteDynamicObject(ctx, strSql);
                    var Ids = XDDDBUtils.ExecuteDateSet(strSQL);

                    strSQL = @"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT @FID, 'CMK_VIP_CardActionFlow', 0, '', '', @OrgID, FBranchID, FCardID, FVIPMEMBERID, 0, 0, 0, 0, 
			                    @Date, @Date, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', '11', @UserID, 0, N'调用卡级别调整接口生成', N''  
		                    FROM CMK_T_VIP_CARD WHERE FCardID = @FCardID ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FID", KDDbType.Int64, Ids.Tables[0].Rows[0]["Id"]));
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@OrgID", KDDbType.Int64, ctx.CurrentOrganizationInfo.ID));
                    lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, ctx.UserId));
                    lstParam.Add(new SqlParam("@Date", KDDbType.DateTime, curDate));

                    //DBUtils.Execute(ctx, strSQL, lstParam);
                    XDDDBUtils.Execute(strSQL, lstParam);

                    scope.Complete();
                }

                result["Result"] = true;
                result["Message"] = "卡级别调整成功";
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("卡级别调整失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 卡有效期调整
        internal string ModifyCardValidDate(Context ctx, string CardNo, string BeginDate, string EndDate, JObject result)
        {
            try
            {
                result["Result"] = false;
                ITimeService timeSvr = Kingdee.BOS.Contracts.ServiceFactory.GetTimeService(ctx);
                var curDate = timeSvr.GetSystemDateTime(ctx);

                string strSql = string.Format(@"SELECT TOP 1 FCardId, FValidControl, FDateStart, FDateEnd, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus, 
                        CASE FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus 
                    FROM CMK_T_VIP_CARD WHERE FNumber = '{0}' ", CardNo);
                var cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (cardDatas == null || cardDatas.Count == 0)
                {
                    result["Message"] = "当前卡在系统中不存在，不允许调整卡有效期！";
                    return result.ToString();
                }

                var cardData = cardDatas.First();

                if (Convert.ToString(cardData["FValidControl"]) != "1")
                {
                    result["Message"] = "当前卡未进行有效期管理，不允许调整卡有效期！";
                    return result.ToString();
                }

                if (Convert.ToString(cardData["FCardStatus"]) != "正常")
                {
                    result["Message"] = string.Format("当前卡状态为【{0}】，不允许调整卡有效期！", Convert.ToString(cardData["FCardStatus"]));
                    return result.ToString();
                }
                if (Convert.ToString(cardData["FFreezeStatus"]) != "正常")
                {
                    result["Message"] = "当前卡已冻结，不允许调整卡有效期！";
                    return result.ToString();
                }

                long lCardId = Convert.ToInt64(cardData["FCardId"]);

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    string strSQL = "";
                    List<SqlParam> lstParam = new List<SqlParam>();

                    strSQL = "UPDATE CMK_T_VIP_CARD SET FDateStart = @FDateStart, FDateEnd = @FDateEnd WHERE FCardId = @FCardId ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@FDateStart", KDDbType.DateTime, BeginDate));
                    lstParam.Add(new SqlParam("@FDateEnd", KDDbType.DateTime, EndDate));

                    DBUtils.Execute(ctx, strSQL, lstParam);

                    //写卡流水
                    strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count = 1 ";
                    var Ids = DBUtils.ExecuteDynamicObject(ctx, strSql);

                    strSQL = @"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT @FID, 'CMK_VIP_CardActionFlow', 0, '', 'CMK_VIP_CardAmountRecharge', @OrgID, FBranchID, FCardID, FVIPMEMBERID, 0, 0, 0, 0, 
			                    @Date, @Date, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', '10', @UserID, 0, N'调用卡有效期调整接口生成', N''  
		                    FROM CMK_T_VIP_CARD WHERE FCardID = @FCardID ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FID", KDDbType.Int64, Ids.First()[0]));
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@OrgID", KDDbType.Int64, ctx.CurrentOrganizationInfo.ID));
                    lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, ctx.UserId));
                    lstParam.Add(new SqlParam("@Date", KDDbType.DateTime, curDate));

                    DBUtils.Execute(ctx, strSQL, lstParam);

                    scope.Complete();
                }

                result["Result"] = true;
                result["Message"] = "卡有效期调整成功";
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("卡有效期调整失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 卡账户有效期调整
        internal string ModifyAcctValidDate(Context ctx, string CardNo, string AccountId, string BeginDate, string EndDate, JObject result)
        {
            try
            {
                result["Result"] = false;
                ITimeService timeSvr = Kingdee.BOS.Contracts.ServiceFactory.GetTimeService(ctx);
                var curDate = timeSvr.GetSystemDateTime(ctx);

                string strSql = string.Format(@"SELECT TOP 1 t1.FCardId, t2.FAcctValidCtrl, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus, 
                        CASE t1.FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus 
                    FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDACCTS t2 ON t1.FCardId = t2.FCardId WHERE t1.FNumber = '{0}' AND t2.FAccountId = {1} ", CardNo, AccountId);
                var cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (cardDatas == null || cardDatas.Count == 0)
                {
                    result["Message"] = "当前卡或者账户在系统中不存在，不允许调整卡账户有效期！";
                    return result.ToString();
                }

                var cardData = cardDatas.First();

                if (Convert.ToString(cardData["FAcctValidCtrl"]) != "1")
                {
                    result["Message"] = "当前账户未进行有效期管理，不允许调整账户有效期！";
                    return result.ToString();
                }

                if (Convert.ToString(cardData["FCardStatus"]) != "正常")
                {
                    result["Message"] = string.Format("当前卡状态为【{0}】，不允许调整账户有效期！", Convert.ToString(cardData["FCardStatus"]));
                    return result.ToString();
                }
                if (Convert.ToString(cardData["FFreezeStatus"]) != "正常")
                {
                    result["Message"] = "当前卡已冻结，不允许调整账户有效期！";
                    return result.ToString();
                }

                long lCardId = Convert.ToInt64(cardData["FCardId"]);

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    string strSQL = "";
                    List<SqlParam> lstParam = new List<SqlParam>();

                    strSQL = @"UPDATE CMK_T_VIP_CARDACCTS SET FAcctDateStart = @FDateStart, FAcctDateEnd = @FDateEnd WHERE FCardId = @FCardId AND FAccountId = @FAccountId 
                        UPDATE CMK_T_VIP_CARD SET FDateStart = @FDateStart WHERE FCardId = @FCardId AND FValidControl = '1' AND FDateStart > @FDateStart
                        UPDATE CMK_T_VIP_CARD SET FDateEnd = @FDateEnd WHERE FCardId = @FCardId AND FValidControl = '1' AND FDateEnd < @FDateEnd ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@FAccountId", KDDbType.Int64, AccountId));
                    lstParam.Add(new SqlParam("@FDateStart", KDDbType.DateTime, BeginDate));
                    lstParam.Add(new SqlParam("@FDateEnd", KDDbType.DateTime, EndDate));

                    DBUtils.Execute(ctx, strSQL, lstParam);

                    //写卡流水
                    strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count = 1 ";
                    var Ids = DBUtils.ExecuteDynamicObject(ctx, strSql);

                    strSQL = @"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT @FID, 'CMK_VIP_CardActionFlow', 0, '', '', @OrgID, FBranchID, FCardID, FVIPMEMBERID, @FAccountId, 0, 0, 0, 
			                    @Date, @Date, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', '10', @UserID, 0, N'调用卡账户有效期调整接口生成', N''  
		                    FROM CMK_T_VIP_CARD WHERE FCardID = @FCardID ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FID", KDDbType.Int64, Ids.First()[0]));
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@FAccountId", KDDbType.Int64, AccountId));
                    lstParam.Add(new SqlParam("@OrgID", KDDbType.Int64, ctx.CurrentOrganizationInfo.ID));
                    lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, ctx.UserId));
                    lstParam.Add(new SqlParam("@Date", KDDbType.DateTime, curDate));

                    DBUtils.Execute(ctx, strSQL, lstParam);

                    scope.Complete();
                }

                result["Result"] = true;
                result["Message"] = "卡账户有效期调整成功";
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("卡账户有效期调整失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 商品账户有效期调整
        internal string ModifySrvAcctValidDate(Context ctx, string CardNo, string AccountId, string BeginDate, string EndDate, JObject result)
        {
            try
            {
                result["Result"] = false;
                ITimeService timeSvr = Kingdee.BOS.Contracts.ServiceFactory.GetTimeService(ctx);
                var curDate = timeSvr.GetSystemDateTime(ctx);

                string strSql = string.Format(@"SELECT TOP 1 t1.FCardId, t2.FIsControlDate, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus, 
                        CASE t1.FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus 
                    FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDSRVACCTS t2 ON t1.FCardId = t2.FCardId WHERE t1.FNumber = '{0}' AND t2.FMaterialId = {1} ", CardNo, AccountId);
                var cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (cardDatas == null || cardDatas.Count == 0)
                {
                    result["Message"] = "当前卡或者账户在系统中不存在，不允许调整卡账户有效期！";
                    return result.ToString();
                }

                var cardData = cardDatas.First();

                if (Convert.ToString(cardData["FIsControlDate"]) != "1")
                {
                    result["Message"] = "当前账户未进行有效期管理，不允许调整账户有效期！";
                    return result.ToString();
                }

                if (Convert.ToString(cardData["FCardStatus"]) != "正常")
                {
                    result["Message"] = string.Format("当前卡状态为【{0}】，不允许调整账户有效期！", Convert.ToString(cardData["FCardStatus"]));
                    return result.ToString();
                }
                if (Convert.ToString(cardData["FFreezeStatus"]) != "正常")
                {
                    result["Message"] = "当前卡已冻结，不允许调整账户有效期！";
                    return result.ToString();
                }

                long lCardId = Convert.ToInt64(cardData["FCardId"]);

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    string strSQL = "";
                    List<SqlParam> lstParam = new List<SqlParam>();

                    strSQL = @"UPDATE CMK_T_VIP_CARDACCTS SET FAccountDateBegin = @FDateStart, FAccountDateEnd = @FDateEnd WHERE FCardId = @FCardId AND FMaterialId = @FAccountId 
                        UPDATE CMK_T_VIP_CARD SET FDateStart = @FDateStart WHERE FCardId = @FCardId AND FValidControl = '1' AND FDateStart > @FDateStart
                        UPDATE CMK_T_VIP_CARD SET FDateEnd = @FDateEnd WHERE FCardId = @FCardId AND FValidControl = '1' AND FDateEnd < @FDateEnd ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@FAccountId", KDDbType.Int64, AccountId));
                    lstParam.Add(new SqlParam("@FDateStart", KDDbType.DateTime, BeginDate));
                    lstParam.Add(new SqlParam("@FDateEnd", KDDbType.DateTime, EndDate));

                    DBUtils.Execute(ctx, strSQL, lstParam);

                    //写卡流水
                    strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count = 1 ";
                    var Ids = DBUtils.ExecuteDynamicObject(ctx, strSql);

                    strSQL = @"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT @FID, 'CMK_VIP_CardActionFlow', 0, '', '', @OrgID, FBranchID, FCardID, FVIPMEMBERID, @FAccountId, 0, 0, 0, 
			                    @Date, @Date, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', '10', @UserID, 0, N'调用商品账户有效期调整接口生成', N''  
		                    FROM CMK_T_VIP_CARD WHERE FCardID = @FCardID ";

                    lstParam = new List<SqlParam>();
                    lstParam.Add(new SqlParam("@FID", KDDbType.Int64, Ids.First()[0]));
                    lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                    lstParam.Add(new SqlParam("@FAccountId", KDDbType.Int64, AccountId));
                    lstParam.Add(new SqlParam("@OrgID", KDDbType.Int64, ctx.CurrentOrganizationInfo.ID));
                    lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, ctx.UserId));
                    lstParam.Add(new SqlParam("@Date", KDDbType.DateTime, curDate));

                    DBUtils.Execute(ctx, strSQL, lstParam);

                    scope.Complete();
                }

                result["Result"] = true;
                result["Message"] = "商品账户有效期调整成功";
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("商品账户有效期调整失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 卡账户数据转移
        internal string TransferCardAccount(Context ctx, string SrcCardNo, string DesCardNo, JObject result)
        {
            try
            {
                result["Result"] = false;
                ITimeService timeSvr = Kingdee.BOS.Contracts.ServiceFactory.GetTimeService(ctx);
                var curDate = timeSvr.GetSystemDateTime(ctx);

                if (SrcCardNo == DesCardNo)
                {
                    result["Message"] = "转出卡号与转入卡号相同，不允许转移卡账户数据！";
                    return result.ToString();
                }

                //转出卡校验
                string strSql = string.Format(@"SELECT TOP 1 FCardId, FCardTypeId, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus, 
                        CASE FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus 
                    FROM CMK_T_VIP_CARD WHERE FNumber = '{0}' ", SrcCardNo);
                var cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (cardDatas == null || cardDatas.Count == 0)
                {
                    result["Message"] = "转出卡号在系统中不存在，不允许转移卡账户数据！";
                    return result.ToString();
                }

                var cardData = cardDatas.First();
                if (Convert.ToString(cardData["FCardStatus"]) != "正常")
                {
                    result["Message"] = string.Format("转出卡状态为【{0}】，不允许转移卡账户数据！", Convert.ToString(cardData["FCardStatus"]));
                    return result.ToString();
                }
                if (Convert.ToString(cardData["FFreezeStatus"]) != "正常")
                {
                    result["Message"] = "转出卡已冻结，不允许转移卡账户数据！";
                    return result.ToString();
                }

                long lSrcCardId = Convert.ToInt64(cardData["FCardId"]);
                long lSrcCardTypeId = Convert.ToInt64(cardData["FCardTypeId"]);

                //转入卡校验
                strSql = string.Format(@"SELECT TOP 1 FCardId, FCardTypeId, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus, 
                        CASE FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus 
                    FROM CMK_T_VIP_CARD WHERE FNumber = '{0}' ", DesCardNo);
                cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (cardDatas == null || cardDatas.Count == 0)
                {
                    result["Message"] = "转入卡号在系统中不存在，不允许转移卡账户数据！";
                    return result.ToString();
                }

                cardData = cardDatas.First();
                if (Convert.ToString(cardData["FCardStatus"]) != "正常")
                {
                    result["Message"] = string.Format("转入卡状态为【{0}】，不允许转移卡账户数据！", Convert.ToString(cardData["FCardStatus"]));
                    return result.ToString();
                }
                if (Convert.ToString(cardData["FFreezeStatus"]) != "正常")
                {
                    result["Message"] = "转入卡已冻结，不允许转移卡账户数据！";
                    return result.ToString();
                }

                long lDesCardId = Convert.ToInt64(cardData["FCardId"]);
                long lDesCardTypeId = Convert.ToInt64(cardData["FCardTypeId"]);

                if (lSrcCardTypeId != lDesCardTypeId)
                {
                    result["Message"] = "转入卡与转入卡类型不一致，不允许转移卡账户数据！";
                    return result.ToString();
                }

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    long FAccountId = 0;
                    decimal FValue = 0M;
                    StringBuilder sbSql = new StringBuilder();
                    List<SqlParam> lstParam = new List<SqlParam>();

                    strSql = string.Format("SELECT FAccountId, FValue FROM CMK_T_VIP_CARDACCTS WHERE FCardId = {0} AND FValue > 0 ", lSrcCardId);
                    var Accts = DBUtils.ExecuteDynamicObject(ctx, strSql);
                    if (Accts != null && Accts.Count > 0)
                    {
                        foreach (var Acct in Accts)
                        {
                            FAccountId = Convert.ToInt64(Acct["FAccountId"]);
                            FValue = Convert.ToDecimal(Acct["FValue"]);

                            sbSql.Clear();
                            sbSql.AppendFormat("UPDATE CMK_T_VIP_CARDACCTS SET FValue = FValue + {0} WHERE FCardId = {1} AND FAccountId = {2} ", FValue, lDesCardId, FAccountId).AppendLine();

                            //写卡流水
                            strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count = 2 ";
                            var Ids = DBUtils.ExecuteDynamicObject(ctx, strSql);

                            sbSql.AppendFormat(@"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT {0}, 'CMK_VIP_CardActionFlow', 0, '', '', {1}, FBranchID, FCardID, FVIPMEMBERID, {2}, '-1', {3}, 0, 
			                    '{4}', '{4}', FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', '23', 16394, 0, N'调用卡账户数据转移接口生成（转出）', N''  
		                    FROM CMK_T_VIP_CARD WHERE FCardID = {5} ", Ids.First()[0], ctx.CurrentOrganizationInfo.ID, FAccountId, FValue, curDate, lSrcCardId);

                            sbSql.AppendFormat(@"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT {0}, 'CMK_VIP_CardActionFlow', 0, '', '', {1}, t1.FBranchID, t1.FCardID, t1.FVIPMEMBERID, t2.FAccountId, '1', {2}, t2.FValue, 
			                    '{3}', '{3}', t1.FCARDLEVELID, t1.FCARDSTATUS, t1.FFREEZESTATUS, t1.FVALIDCONTROL, t1.FDATESTART, t1.FDATEEND, '', '23', 16394, 0, N'调用卡账户数据转移接口生成（转入）', N''  
		                    FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDACCTS t2 ON t1.FCardID = t2.FCardID
                                WHERE t1.FCardID = {4} AND t2.FAccountId = {5} ", Ids.First()[1], ctx.CurrentOrganizationInfo.ID, FValue, curDate, lDesCardId, FAccountId);

                            DBUtils.Execute(ctx, sbSql.ToString());
                        }
                    }

                    strSql = string.Format("SELECT FMaterialId, FCountctl FROM CMK_T_VIP_CARDSRVACCTS WHERE FCardId = {0} AND FValue > 0 ", lSrcCardId);
                    Accts = DBUtils.ExecuteDynamicObject(ctx, strSql);
                    if (Accts != null && Accts.Count > 0)
                    {
                        foreach (var Acct in Accts)
                        {
                            FAccountId = Convert.ToInt64(Acct["FMaterialId"]);
                            FValue = Convert.ToDecimal(Acct["FCountctl"]);

                            sbSql.Clear();
                            sbSql.AppendFormat("UPDATE CMK_T_VIP_CARDSRVACCTS SET FCountctl = FCountctl + {0} WHERE FCardId = {1} AND FMaterialId = {2} ", FValue, lDesCardId, FAccountId).AppendLine();

                            //写卡流水
                            strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count = 2 ";
                            var Ids = DBUtils.ExecuteDynamicObject(ctx, strSql);

                            sbSql.AppendFormat(@"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT {0}, 'CMK_VIP_CardActionFlow', 0, '', '', {1}, FBranchID, FCardID, FVIPMEMBERID, {2}, '-1', {3}, 0, 
			                    '{4}', '{4}', FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', '23', 16394, 0, N'调用卡账户数据转移接口生成（转出）', N''  
		                    FROM CMK_T_VIP_CARD WHERE FCardID = {5} ", Ids.First()[0], ctx.CurrentOrganizationInfo.ID, FAccountId, FValue, curDate, lSrcCardId);

                            sbSql.AppendFormat(@"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT {0}, 'CMK_VIP_CardActionFlow', 0, '', '', {1}, t1.FBranchID, t1.FCardID, t1.FVIPMEMBERID, t2.FAccountId, '1', {2}, t2.FCountctl, 
			                    '{3}', '{3}', t1.FCARDLEVELID, t1.FCARDSTATUS, t1.FFREEZESTATUS, t1.FVALIDCONTROL, t1.FDATESTART, t1.FDATEEND, '', '23', 16394, 0, N'调用卡账户数据转移接口生成（转入）', N''  
		                    FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDSRVACCTS t2 ON t1.FCardID = t2.FCardID
                                WHERE t1.FCardID = {4} AND t2.FAccountId = {5} ", Ids.First()[1], ctx.CurrentOrganizationInfo.ID, FValue, curDate, lDesCardId, FAccountId);

                            DBUtils.Execute(ctx, sbSql.ToString());
                        }
                    }

                    sbSql.Clear();
                    sbSql.AppendFormat("UPDATE CMK_T_VIP_CARDACCTS SET FValue = 0 WHERE FCardId = {0} ", lSrcCardId).AppendLine();
                    sbSql.AppendFormat("UPDATE CMK_T_VIP_CARDSRVACCTS SET FCountctl = 0 WHERE FCardId = {0} ", lSrcCardId).AppendLine();
                    sbSql.AppendFormat("UPDATE CMK_T_VIP_CARD SET FCardStatus = 'X' WHERE FCardId = {0} ", lSrcCardId).AppendLine();
                    DBUtils.Execute(ctx, sbSql.ToString());

                    scope.Complete();
                }

                JObject resCard = new JObject();
                resCard.Add("Result", false);
                resCard.Add("Message", "");
                resCard.Add("Data", string.Empty);
                this.QueryVIPCardInfo(ctx, DesCardNo, "", resCard);

                result["Result"] = true;
                result["Data"] = resCard["Data"];
                result["Message"] = "卡账户有效期调整成功";
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("卡账户有效期调整失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 卡账户交易Old
        internal string CardAcctTransActionOld(Context ctx, string strParams, string TransSerial, JObject result)
        {
            try
            {
                string strSQL = "";
                string CardNo = "";        //卡号
                string BranchNumber = "";  //门店编码
                string BillNo = "";        //交易单号
                string FOperType = "";     //业务类型
                string AccountId = "";     //卡账户
                string FOption = "";       //发生方向
                string FOperValue = "";    //发生额
                string FGiveAmount = "";   //赠送额
                string Note = "";          //备注
                string strOperType = "消费";
                string IsApplets = "false"; //默认是实体卡的调用

                decimal dValue = 0M;
                decimal dGiveValue = 0M;
                decimal dBalValue = 0M;

                result["Result"] = false;

                JObject jParams = JObject.Parse(strParams);

                CardNo = CommonService.GetJParamString(jParams, "CardNo");
                if (string.IsNullOrWhiteSpace(CardNo))
                {
                    result["Message"] = "参数【CardNo：卡号】未设置！";
                    return result.ToString();
                }

                //区分实体和付款码消费标识  IsApplets 默认否
                IsApplets = CommonService.GetJParamString(jParams, "IsApplets");
                if (IsApplets == "false")
                {
                    //校验实体卡密码
                    string get_card_password = CommonService.GetJParamString(jParams, "CardPassWord");
                    if (CommonService.CheckCardPassWord(get_card_password, CardNo))
                    {
                        result["Message"] = "消费密码错误！请重新输入密码。";
                        return result.ToString();
                    }
                }


                DateTime curDate = DateTime.Now;
                BranchNumber = CommonService.GetJParamString(jParams, "BranchNumber");
                if (string.IsNullOrWhiteSpace(BranchNumber))
                {
                    result["Message"] = "参数【BranchNumber：门店编码】未设置！";
                    return result.ToString();
                }
                long lBranchId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", BranchNumber);
                if (lBranchId == 0)
                {
                    result["Message"] = "参数【BranchNumber：门店编码】在系统中不存在！";
                    return result.ToString();
                }

                //BillNo = CommonService.GetJParamString(jParams, "BillNo");
                //if (string.IsNullOrWhiteSpace(BillNo))
                //{
                //    result["Message"] = "参数【BillNo：交易单号】未设置！";
                //    return result.ToString();
                //}

                //单号改成系统自动生成 格式：日期+交易序列号

                BillNo = "SG" + DateTime.Now.ToString("yyyyMMdd") + TransSerial;

                FOperType = CommonService.GetJParamString(jParams, "FOperType");

                if (string.IsNullOrWhiteSpace(FOperType))
                {
                    result["Message"] = "参数【FOperType：业务类型】未设置！";
                    return result.ToString();
                }
                //03-消费 04-充值 05-积分返利 08-金额调整 09-积分调整
                if (FOperType != "03" && FOperType != "04" && FOperType != "05" && FOperType != "06" && FOperType != "08" && FOperType != "09")
                {
                    result["Message"] = "参数【FOperType：业务类型】设置错误！";
                    return result.ToString();
                }

                Note = CommonService.GetJParamString(jParams, "Note");

                if (string.IsNullOrWhiteSpace(Note))
                {
                    Note = (Convert.ToBoolean(IsApplets) == true ? "小程序" : "寺冈") + "调用卡交易接口生成";

                    switch (FOperType)
                    {
                        case "03":
                            strOperType = "消费";
                            break;
                        case "04":
                            strOperType = "充值";
                            break;
                        case "05":
                            strOperType = "积分返利";
                            break;
                        case "06":
                            strOperType = "积分转储值";
                            break;
                        case "08":
                            strOperType = "金额调整";
                            break;
                        case "09":
                            strOperType = "积分调整";
                            break;
                    }

                    Note = string.Format("{0}【{1}】", Note, strOperType);
                }

                var dataAccts = jParams["dataAccts"] as JArray;
                if (dataAccts == null || dataAccts.Count == 0)
                {
                    result["Message"] = "参数【dataAccts：卡账户数据包】未设置！";
                    return result.ToString();
                }

                JArray datas = new JArray();
                //using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                //{
                foreach (JObject dataAcct in dataAccts)
                {
                    AccountId = CommonService.GetJParamString(dataAcct, "AccountId");
                    if (string.IsNullOrWhiteSpace(AccountId))
                    {
                        result["Message"] = "参数【AccountId：卡账户】未设置！";
                        return result.ToString();
                    }

                    FOption = CommonService.GetJParamString(dataAcct, "FOption");
                    if (string.IsNullOrWhiteSpace(FOption))
                    {
                        result["Message"] = "参数【FOption：发生方向】未设置！";
                        return result.ToString();
                    }
                    if (FOption != "1" && FOption != "-1")
                    {
                        result["Message"] = "参数【FOption：发生方向】设置错误，只能为 1 或者 -1 ！";
                        return result.ToString();
                    }

                    //发生额
                    FOperValue = CommonService.GetJParamString(dataAcct, "FOperValue");
                    if (string.IsNullOrWhiteSpace(FOperValue))
                    {
                        result["Message"] = "参数【FOperValue：发生额】未设置！";
                        return result.ToString();
                    }
                    if (!decimal.TryParse(FOperValue, out dValue) || dValue <= 0M)
                    {
                        result["Message"] = "参数【FOperValue：发生额】设置错误，必须大于0 ！";
                        return result.ToString();
                    }

                    //赠送金额
                    FGiveAmount = CommonService.GetJParamString(dataAcct, "FGiveAmount");
                    if (!decimal.TryParse(FGiveAmount, out dGiveValue) || dGiveValue < 0M)
                    {
                        result["Message"] = "参数【FGiveAmount：赠送额】设置错误！";
                        return result.ToString();
                    }

                    //查找储值账户对应数据
                    strSQL = string.Format(@"SELECT TOP 1 t1.FCardId, t1.FValidControl, t1.FDateStart, t1.FDateEnd, t2.FAcctValidCtrl, t2.FAcctDateStart, t2.FAcctDateEnd, t2.FValue, 
                                CASE t1.FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus, 
                                t2.FAcctDateEnd, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus 
                            FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDACCTS t2 ON t1.FCardId = t2.FCardId WHERE t1.FNumber = '{0}' AND t2.FAccountId = {1} ", CardNo, AccountId);
                    //var cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSQL);
                    DataSet cardDatas = XDDDBUtils.ExecuteDateSet(strSQL);
                    if (cardDatas == null || cardDatas.Tables.Count == 0)
                    {
                        result["Message"] = "未找到对应的卡号和卡账户信息，不允许交易！";
                        return result.ToString();
                    }
                    //var cardData = cardDatas.First();
                    var cardData = cardDatas.Tables[0].Rows[0];
                    if (Convert.ToString(cardData["FCardStatus"]) != "正常")
                    {
                        result["Message"] = string.Format("当前卡状态为【{0}】，不允许交易！", Convert.ToString(cardData["FCardStatus"]));
                        return result.ToString();
                    }
                    if (Convert.ToString(cardData["FFreezeStatus"]) != "正常")
                    {
                        result["Message"] = "当前卡已冻结，不允许交易！";
                        return result.ToString();
                    }
                    if (Convert.ToString(cardData["FValidControl"]) == "1" && (Convert.ToDateTime(cardData["FDateStart"]) > curDate || Convert.ToDateTime(cardData["FDateEnd"]) < curDate))
                    {
                        result["Message"] = string.Format("当前卡不在有效期内，不允许交易！", Convert.ToString(cardData["FCardStatus"]));
                        return result.ToString();
                    }
                    if (Convert.ToString(cardData["FAcctValidCtrl"]) == "1" && (Convert.ToDateTime(cardData["FAcctDateStart"]) > curDate || Convert.ToDateTime(cardData["FAcctDateEnd"]) < curDate))
                    {
                        result["Message"] = string.Format("当前账户不在有效期内，不允许交易！", Convert.ToString(cardData["FCardStatus"]));
                        return result.ToString();
                    }
                    if (FOption == "-1" && dValue > Convert.ToDecimal(cardData["FValue"]))
                    {
                        result["Message"] = "当前账户余额不足，不允许交易！";
                        return result.ToString();
                    }

                    if (!this.CheckCardUseBranch(ctx, lBranchId, CardNo, result)) //检查使用门店
                    {
                        return result.ToString();
                    }

                    long lCardId = Convert.ToInt64(cardData["FCardId"]);
                    decimal dCurValue = Convert.ToDecimal(cardData["FValue"]);
                    dBalValue = (FOption == "1" ? dCurValue + dValue : dCurValue - dValue);
                    List<SqlParam> lstParam = new List<SqlParam>();

                    //04-充值 生成卡金额充值单 结算方式按照银行卡？
                    if (FOperType == "04" && AccountId == "2" && FOption == "1")   //卡金额充值
                    {
                        strSQL = "EXEC CMK_PR_POSVIPCardRecharge @UserID, 0, @CardNumber, @CardAccID, @BranchID, @RechargeValue, 0, @RechargeValue, 1, 0, 0, @TransSerial, @Note, 0, 0, 0, @FBillNO ";

                        lstParam = new List<SqlParam>();
                        lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, 0));
                        lstParam.Add(new SqlParam("@CardNumber", KDDbType.String, CardNo));
                        lstParam.Add(new SqlParam("@CardAccID", KDDbType.Int64, 2));
                        lstParam.Add(new SqlParam("@BranchID", KDDbType.Int64, lBranchId));
                        lstParam.Add(new SqlParam("@RechargeValue", KDDbType.Decimal, dValue));
                        lstParam.Add(new SqlParam("@TransSerial", KDDbType.String, TransSerial));
                        lstParam.Add(new SqlParam("@Note", KDDbType.String, Note));
                        lstParam.Add(new SqlParam("@FBillNO", KDDbType.String, BillNo));

                        XDDDBUtils.Execute(strSQL, lstParam);
                    }
                    else
                    {
                        strSQL = "UPDATE CMK_T_VIP_CARDACCTS SET FValue = @BalValue WHERE FCardId = @FCardId AND FACCOUNTID = @CardAccID ";

                        lstParam = new List<SqlParam>();
                        lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                        lstParam.Add(new SqlParam("@CardAccID", KDDbType.Int64, AccountId));
                        lstParam.Add(new SqlParam("@BalValue", KDDbType.Decimal, dBalValue));

                        XDDDBUtils.Execute(strSQL, lstParam);

                        //写卡流水
                        strSQL = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count = 1 ";
                        //var Ids = DBUtils.ExecuteDynamicObject(ctx, strSQL);
                        var Idrs = XDDDBUtils.ExecuteDateSet(strSQL);
                        DataRow dr = Idrs.Tables[0].Rows[0];
                        strSQL = @"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, 
			                    FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
		                    SELECT @FID, 'CMK_VIP_CardActionFlow', 0, @FBillNO, '', @OrgID, @BranchID, FCardID, FVIPMEMBERID, @CardAccID, @FOption, @OperValue, @BalValue, 
			                    @Date, @Date, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', @OperType, @UserID, 0, @Note, @TransSerial  
		                    FROM CMK_T_VIP_CARD WHERE FCardID = @FCardID ";

                        lstParam = new List<SqlParam>();
                        lstParam.Add(new SqlParam("@FID", KDDbType.Int64, dr[0].ToString()));
                        lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                        lstParam.Add(new SqlParam("@CardAccID", KDDbType.Int64, AccountId));
                        lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, 0));
                        lstParam.Add(new SqlParam("@OrgID", KDDbType.Int64, 1));
                        lstParam.Add(new SqlParam("@BranchID", KDDbType.Int64, lBranchId));
                        lstParam.Add(new SqlParam("@FOption", KDDbType.String, FOption));
                        lstParam.Add(new SqlParam("@OperValue", KDDbType.Decimal, dValue));
                        lstParam.Add(new SqlParam("@BalValue", KDDbType.Decimal, dBalValue));
                        lstParam.Add(new SqlParam("@OperType", KDDbType.String, FOperType));
                        lstParam.Add(new SqlParam("@Date", KDDbType.DateTime, curDate));
                        lstParam.Add(new SqlParam("@FBillNO", KDDbType.String, BillNo));
                        lstParam.Add(new SqlParam("@Note", KDDbType.String, Note));
                        lstParam.Add(new SqlParam("@TransSerial", KDDbType.String, TransSerial));

                        XDDDBUtils.Execute(strSQL, lstParam);
                    }

                    JObject data = new JObject();
                    data.Add("AccountId", AccountId);
                    data.Add("OldValue", dCurValue);
                    data.Add("BalValue", dBalValue);
                    datas.Add(data);
                }

                //    scope.Complete();
                //}

                foreach (JObject dataAcct in dataAccts)
                {
                    AccountId = CommonService.GetJParamString(dataAcct, "AccountId");
                    FOption = CommonService.GetJParamString(dataAcct, "FOption");
                    FOperValue = CommonService.GetJParamString(dataAcct, "FOperValue");

                    strSQL = string.Format(@"SELECT TOP 1 t1.FMobile, t4.FName AS FAccount, CONVERT(DECIMAL(20, 2), t3.FValue) AS FBalance FROM CMK_T_VIP_Member t1 
                        INNER JOIN CMK_T_VIP_CARD t2 ON t2.FVIPMemberID = t1.FVIPID 
                        INNER JOIN CMK_T_VIP_CARDACCTS t3 ON t2.FCardId = t3.FCardId INNER JOIN CMK_T_VIP_CARDACCT_L t4 ON t3.FAccountID = t4.FCardAcctID AND t4.FLocaleId = 2052 
                        WHERE t2.FNumber = '{0}' AND  t3.FAccountID = {1} ", CardNo, AccountId);
                    DataSet cardAccts = XDDDBUtils.ExecuteDateSet(strSQL);
                    //var cardAccts = DBUtils.ExecuteDynamicObject(ctx, strSQL);
                    if (cardAccts != null && cardAccts.Tables.Count > 0)
                    {
                        var cardAcct = cardAccts.Tables[0].Rows[0];
                        //var cardAcct = cardAccts.First();
                        string MobileNo = Convert.ToString(cardAcct["FMobile"]);
                        string AcctName = Convert.ToString(cardAcct["FAccount"]);
                        dBalValue = Convert.ToDecimal(cardAcct["FBalance"]);
                        if (!string.IsNullOrWhiteSpace(MobileNo))
                        {
                            //对接短信通知接口 沃谷的短信通知统一在接口结束后进行发送
                            //string strSmsContent = string.Format(@"您的会员卡({0})账户({1})于{2}发生（{3}）,{4}值{5}，当前余额{6}
                            //", CardNo, AcctName, DateTime.Now, strOperType, FOption == "1" ? "增加" : "减少", FOperValue, dBalValue);
                            //ESBSmsService smsService = new ESBSmsService();
                            //smsService.SendSmsService(MobileNo, strSmsContent);
                        }
                    }
                }

                result["Result"] = true;
                result["Data"] = datas;
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("交易失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 卡账户交易冲正Old
        internal string CardAcctTransActionUndoOld(Context ctx, string strParams, string TransSerial, JObject result)
        {
            try
            {
                string CardNo = "";        //卡号
                string AccountId = "";     //卡账户
                string BranchNumber = "";  //门店编码

                string FRecType = ""; //冲正类型  01：退款冲正  02：异常冲正

                result["Result"] = false;
                JObject jParams = JObject.Parse(strParams);
                DateTime curDate = DateTime.Now;

                FRecType = CommonService.GetJParamString(jParams, "FOperType");  //将冲正记录区分

                BranchNumber = CommonService.GetJParamString(jParams, "BranchNumber");
                if (string.IsNullOrWhiteSpace(BranchNumber))
                {
                    result["Message"] = "参数【BranchNumber：门店编码】未设置！";
                    return result.ToString();
                }
                long lBranchId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", BranchNumber);
                if (lBranchId == 0)
                {
                    result["Message"] = "参数【BranchNumber：门店编码】在系统中不存在！";
                    return result.ToString();
                }

                CardNo = CommonService.GetJParamString(jParams, "CardNo");
                if (string.IsNullOrWhiteSpace(CardNo))
                {
                    result["Message"] = "参数【CardNo：卡号】未设置！";
                    return result.ToString();
                }

                var dataAccts = jParams["dataAccts"] as JArray;
                if (dataAccts == null || dataAccts.Count == 0)
                {
                    result["Message"] = "参数【dataAccts：卡账户数据包】未设置！";
                    return result.ToString();
                }

                JArray datas = new JArray();
                //using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                //{
                foreach (JObject dataAcct in dataAccts)
                {

                    AccountId = CommonService.GetJParamString(dataAcct, "AccountId");
                    if (string.IsNullOrWhiteSpace(AccountId))
                    {
                        result["Message"] = "参数【AccountId：卡账户】未设置！";
                        return result.ToString();
                    }

                    string strSQL = string.Format(@"SELECT TOP 1 t1.FCardId, t2.FValue FROM CMK_T_VIP_CARD t1 
                            INNER JOIN CMK_T_VIP_CARDACCTS t2 ON t1.FCardId = t2.FCardId WHERE t1.FNumber = '{0}' AND t2.FAccountId = {1} ", CardNo, AccountId);
                    DataSet cardDatas = XDDDBUtils.ExecuteDateSet(strSQL);
                    //var cardDatas = DBUtils.ExecuteDynamicObject(ctx, strSQL);
                    if (cardDatas == null || cardDatas.Tables.Count == 0)
                    {
                        result["Message"] = "未找到对应的卡号和卡账户信息，交易冲正失败！";
                        return result.ToString();
                    }
                    //var cardData = cardDatas.First();
                    var cardData = cardDatas.Tables[0].Rows[0];
                    long lCardId = Convert.ToInt64(cardData["FCardId"]);
                    decimal dCurValue = Convert.ToDecimal(cardData["FValue"]);

                    //查询储值账户信息
                    strSQL = string.Format(@"SELECT TOP 1 FOPTION, FOPERVALUE, FOPERATIONTYPE FROM CMK_VIP_T_CardAction 
                            WHERE FCardID = {0} AND FACCOUNTID = {1} AND FTRANSSERIAL = '{2}' ", lCardId, AccountId, TransSerial);
                    DataSet acctDatas = XDDDBUtils.ExecuteDateSet(strSQL);
                    //var acctDatas = DBUtils.ExecuteDynamicObject(ctx, strSQL);
                    if (acctDatas == null || acctDatas.Tables.Count == 0)
                    {
                        result["Message"] = "未找到交易序列号对应的数据记录，交易冲正失败！";
                        return result.ToString();
                    }
                    var acctData = acctDatas.Tables[0].Rows[0];
                    //var acctData = acctDatas.First();
                    string FOption = Convert.ToString(acctData["FOPTION"]);
                    string FOperType = Convert.ToString(acctData["FOPERATIONTYPE"]);
                    decimal FOperValue = Convert.ToDecimal(acctData["FOPERVALUE"]);
                    decimal dBalValue = (FOption == "1" ? dCurValue - FOperValue : dCurValue + FOperValue);

                    List<SqlParam> lstParam = new List<SqlParam>();

                    if (FOperType == "04" && AccountId == "2" && FOption == "1")  //卡金额充值
                    {
                        //储值账户冲正
                        strSQL = "EXEC CMK_PR_POSVIPCardRechargeUndo @UserID, 0, @CardNumber, @CardAccID, @BranchID, @RechargeValue, 0, @RechargeValue, 1, 0, 0, @TransSerial, @Note ";
                        lstParam = new List<SqlParam>();
                        lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, 0));
                        lstParam.Add(new SqlParam("@CardNumber", KDDbType.String, CardNo));
                        lstParam.Add(new SqlParam("@CardAccID", KDDbType.Int64, 2));
                        lstParam.Add(new SqlParam("@BranchID", KDDbType.Int64, lBranchId));
                        lstParam.Add(new SqlParam("@RechargeValue", KDDbType.Decimal, FOperValue));
                        lstParam.Add(new SqlParam("@TransSerial", KDDbType.String, TransSerial));
                        lstParam.Add(new SqlParam("@Note", KDDbType.String, "卡账户交易冲正"));
                        XDDDBUtils.Execute(strSQL, lstParam);
                    }
                    else
                    {
                        strSQL = "UPDATE CMK_T_VIP_CARDACCTS SET FValue = @BalValue WHERE FCardId = @FCardId AND FACCOUNTID = @CardAccID ";
                        lstParam = new List<SqlParam>();
                        lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                        lstParam.Add(new SqlParam("@CardAccID", KDDbType.Int64, AccountId));
                        lstParam.Add(new SqlParam("@BalValue", KDDbType.Decimal, dBalValue));

                        XDDDBUtils.Execute(strSQL, lstParam);

                        //插入卡交易流水冲正记录
                        strSQL = @"  
	                            INSERT INTO CMK_VIP_T_CardActUndoBK(FID,FFORMID,FBILLNO,FBIZTYPE,FCARDID,FACCOUNTID,FORGID,FCHANNELID,FBIZDATE,FRECORDDATETIME,FPOSID,FOPTION,FOPERVALUE,FBALANCE,FNOTE,FOPERATIONTYPE,FCARDSTATUS,FFREEZESTATUS,FOPERATORID,FTRANSSERIAL,FCONSUMESTATUS)
	                            SELECT FID,FFORMID,FBILLNO,FBIZTYPE,FCARDID,FACCOUNTID,FORGID,FCHANNELID,FBIZDATE,FRECORDDATETIME,FPOSID,FOPTION,FOPERVALUE,FBALANCE,FNOTE,FOPERATIONTYPE,FCARDSTATUS,FFREEZESTATUS,FOPERATORID,FTRANSSERIAL,FCONSUMESTATUS 
		                            FROM CMK_VIP_T_CardAction WHERE FCardID = @FCardID AND FACCOUNTID = @CardAccID AND FTRANSSERIAL = @TransSerial
  
	                            INSERT INTO CMK_VIP_T_CardActUndo(FID,FBILLNO,FBIZTYPE,FCARDID,FACCOUNTID,FORGID,FCHANNELID,FCARDLEVELID,FBIZDATE,FRECORDDATETIME,FPOSID,FBEFOREBALANCE,FOPTION,FOPERVALUE,FBALANCE,FNOTE,FOPERATIONTYPE,FBILLID,FMEMBERID,FOPERATORID,FMATERIALID,FTRANSSERIAL)
	                            SELECT FID,FBILLNO,FBIZTYPE,FCARDID,FACCOUNTID, FORGID, FBRANCHID, FCARDLEVELID,@Date,@Date,0,FBALANCE, FOPTION, FOPERVALUE, FBALANCE-FOPTION*FOPERVALUE, @Note, FOPERATIONTYPE,FBILLID,FMEMBERID,@UserID,FMATERIALID,FTRANSSERIAL 
		                            FROM CMK_VIP_T_CardAction WHERE FCardID = @FCardID AND FACCOUNTID = @CardAccID AND FTRANSSERIAL = @TransSerial 

                                DELETE CMK_VIP_T_CardAction WHERE FCardID = @FCardID AND FACCOUNTID = @CardAccID AND FTRANSSERIAL = @TransSerial ";

                        lstParam = new List<SqlParam>();
                        lstParam.Add(new SqlParam("@FCardId", KDDbType.Int64, lCardId));
                        lstParam.Add(new SqlParam("@CardAccID", KDDbType.Int64, AccountId));
                        lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, ctx.UserId));
                        lstParam.Add(new SqlParam("@Date", KDDbType.DateTime, curDate));
                        lstParam.Add(new SqlParam("@TransSerial", KDDbType.String, TransSerial));
                        lstParam.Add(new SqlParam("@Note", KDDbType.String, "卡账户交易冲正"));

                        XDDDBUtils.Execute(strSQL, lstParam);
                    }

                    JObject data = new JObject();
                    data.Add("AccountId", AccountId);
                    data.Add("OldValue", dCurValue);
                    data.Add("BalValue", dBalValue);
                    datas.Add(data);
                }

                //    scope.Complete();
                //}

                result["Result"] = true;
                result["Message"] = "交易冲正成功";
                result["Data"] = datas;
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("交易冲正失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 卡账户交易New
        internal string CardAcctTransAction(Context ctx, string strParams, string TransSerial, JObject result, string IsApplets = "true")
        {
            try
            {
                JArray array;
                string str = "";
                string jParamString = "";
                string str3 = "";
                string str4 = "";
                string str5 = "";
                string str6 = "";
                string s = "";
                string str8 = "";
                string str_note = "";

                result["Result"] = false;
                JObject jParams = JObject.Parse(strParams);
                //DateTime systemDateTime = ServiceFactory.GetTimeService(ctx).GetSystemDateTime(ctx);
                DateTime systemDateTime = DateTime.Now;
                //string Fmark = CommonService.GetJParamString(jParams, "Fmark");
                jParamString = CommonService.GetJParamString(jParams, "BranchNumber");
                if (string.IsNullOrWhiteSpace(jParamString))
                {
                    result["Message"] = ResManager.LoadKDString("参数【BranchNumber：门店编码】未设置！", "017178000000462", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                long num = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", jParamString, 0L);
                if (num == 0L)
                {
                    result["Message"] = ResManager.LoadKDString("参数【BranchNumber：门店编码】在系统中不存在！", "017178000000452", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                //获取当前组织id
                //string strSql = string.Format("SELECT FORGID FROM CMK_LS_BRANCH WHERE FID={0}", num);
                string strSql = "";
                long iD = 1L;//DBUtils.ExecuteScalar<long>(ctx, strSql, 0L, new SqlParam[0]);
                if (iD == 0L)
                {
                    //iD = ctx.CurrentOrganizationInfo.ID;
                }
                str = CommonService.GetJParamString(jParams, "CardNo");
                if (string.IsNullOrWhiteSpace(str))
                {
                    result["Message"] = ResManager.LoadKDString("参数【CardNo：卡号】未设置！", "017178000001782", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                str4 = CommonService.GetJParamString(jParams, "FOperType");

                //区分实体和付款码消费标识  IsApplets 默认否
                if (IsApplets == "true")
                {
                    //LogHelper.WirteLog("小程序", "卡账户交易调用日志：", jParams.ToString());
                    str_note = "小程序调用";
                    str3 = CommonService.GetJParamString(jParams, "BillNo");
                    if (string.IsNullOrWhiteSpace(str3))
                    {
                        result["Message"] = ResManager.LoadKDString("参数【BillNo：交易单号】未设置！", "017178000001783", SubSystemType.RETAIL, new object[0]);
                        return result.ToString();
                    }
                }
                else
                {
                    //LogHelper.WirteLog("寺冈", "卡账户交易调用日志：", jParams.ToString());
                    str_note = "寺冈收银调用";
                    //寺冈调用：单号改成系统自动生成 格式：日期+交易序列号
                    str3 = "SG" + DateTime.Now.ToString("yyyyMMdd") + TransSerial;
                    //卡是否凭密码消费-校验实体卡密码

                    //string get_card_password = CommonService.GetJParamString(jParams, "CardPassWord");
                    //if (!CommonService.CheckCardPassWord(get_card_password, str))
                    //{
                    //    result["Message"] = "消费密码错误！请重新输入密码。";
                    //    return result.ToString();
                    //}
                    //寺冈调用消费接口 FOperType固定为08  分别用于消费和退款
                    str4 = "08";
                }

                if (string.IsNullOrWhiteSpace(str4))
                {
                    result["Message"] = ResManager.LoadKDString("参数【FOperType：业务类型】未设置！", "017178000001784", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                if (((((str4 != "03") && (str4 != "04")) && ((str4 != "05") && (str4 != "06"))) && (str4 != "08")) && (str4 != "09"))
                {
                    result["Message"] = ResManager.LoadKDString("参数【FOperType：业务类型】设置错误！", "017178000001785", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                str8 = CommonService.GetJParamString(jParams, "Note");
                if (!string.IsNullOrWhiteSpace(str8))
                {
                    goto Label_045B;
                }
                str8 = str_note + ResManager.LoadKDString("调用卡交易接口生成", "017178000001786", SubSystemType.RETAIL, new object[0]);
                string str10 = ResManager.LoadKDString("消费", "017178000001787", SubSystemType.RETAIL, new object[0]);
                string str14 = str4;
                if (str14 != null)
                {
                    if (str14 != "03")
                    {
                        if (str14 == "04")
                        {
                            goto Label_03C3;
                        }
                        if (str14 == "05")
                        {
                            goto Label_03DE;
                        }
                        if (str14 == "06")
                        {
                            goto Label_03F9;
                        }
                        if (str14 == "08")
                        {
                            goto Label_0414;
                        }
                        if (str14 == "09")
                        {
                            goto Label_042F;
                        }
                    }
                    else
                    {
                        str10 = ResManager.LoadKDString("消费", "017178000001787", SubSystemType.RETAIL, new object[0]);
                    }
                }
                goto Label_044A;
            Label_03C3:
                str10 = ResManager.LoadKDString("充值", "017178000001788", SubSystemType.RETAIL, new object[0]);
                goto Label_044A;
            Label_03DE:
                str10 = ResManager.LoadKDString("积分返利", "017178000001789", SubSystemType.RETAIL, new object[0]);
                goto Label_044A;
            Label_03F9:
                str10 = ResManager.LoadKDString("积分转储值", "017178000001790", SubSystemType.RETAIL, new object[0]);
                goto Label_044A;
            Label_0414:
                str10 = ResManager.LoadKDString("金额调整", "017178000001791", SubSystemType.RETAIL, new object[0]);
                goto Label_044A;
            Label_042F:
                str10 = ResManager.LoadKDString("积分调整", "017178000001792", SubSystemType.RETAIL, new object[0]);
            Label_044A:
                str8 = string.Format("{0}【{1}】", str8, str10);
            Label_045B:
                array = jParams["dataAccts"] as JArray;
                if ((array == null) || (array.Count == 0))
                {
                    result["Message"] = ResManager.LoadKDString("参数【dataAccts：卡账户数据包】未设置！", "017178000001793", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                string str11 = CommonService.GetJParamString(jParams, "SettleAmt");
                decimal num3 = 0M;
                decimal.TryParse(s, out num3);
                JArray array2 = new JArray();
                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    foreach (JObject obj3 in (IEnumerable<JToken>)array)
                    {
                        str5 = CommonService.GetJParamString(obj3, "AccountId");
                        if (string.IsNullOrWhiteSpace(str5))
                        {
                            result["Message"] = ResManager.LoadKDString("参数【AccountId：卡账户】未设置！", "017178000001794", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }

                        str6 = CommonService.GetJParamString(obj3, "FOption");

                        if (string.IsNullOrWhiteSpace(str6))
                        {
                            result["Message"] = ResManager.LoadKDString("参数【FOption：发生方向】未设置！", "017178000001795", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        if ((str6 != "1") && (str6 != "-1"))
                        {
                            result["Message"] = ResManager.LoadKDString("参数【FOption：发生方向】设置错误，只能为 1 或者 -1 ！", "017178000001796", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        //发生额：分为单位  2021-05-13 与寺冈顾工沟通
                        s = CommonService.GetJParamString(obj3, "FOperValue");
                        if (string.IsNullOrWhiteSpace(s))
                        {
                            result["Message"] = ResManager.LoadKDString("参数【FOperValue：发生额】未设置！", "017178000001797", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        decimal num4 = 0M;
                        if (!(decimal.TryParse(s, out num4) && (num4 > 0M)))
                        {
                            result["Message"] = ResManager.LoadKDString("参数【FOperValue：发生额】设置错误，必须大于0 ！", "017178000001798", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        num4 = num4 / 100;

                        decimal num5 = 0M;
                        decimal.TryParse(CommonService.GetJParamString(obj3, "FGiveAmount"), out num5);
                        num5 = num5 / 100;

                        decimal num6 = 0M;
                        decimal.TryParse(CommonService.GetJParamString(obj3, "FGivePoint"), out num6);
                        strSql = string.Format("SELECT TOP 1 t1.FCardId, t1.FValidControl, t1.FDateStart, t1.FDateEnd, t2.FAcctValidCtrl, t2.FAcctDateStart, t2.FAcctDateEnd, t2.FValue, CASE t1.FCARDSTATUS WHEN 'E' THEN '空卡' WHEN 'A' THEN '正常' WHEN 'G' THEN '挂失' WHEN 'X' THEN '销户' WHEN 'T' THEN '退卡' END AS FCardStatus, t2.FAcctDateEnd, CASE FFreezeStatus WHEN 'B' THEN '冻结' ELSE '正常' END AS FFreezeStatus FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDACCTS t2 ON t1.FCardId = t2.FCardId WHERE t1.FNumber = '{0}' AND t2.FAccountId = {1}"
                            , str, str5);
                        //DynamicObjectCollection source = DBUtils.ExecuteDynamicObject(ctx, strSql, null, null, CommandType.Text, new SqlParam[0]);
                        DataSet source = XDDDBUtils.ExecuteDateSet(strSql);

                        if ((source == null) || (source.Tables[0].Rows.Count == 0))
                        {
                            result["Message"] = ResManager.LoadKDString("未找到对应的卡号和卡账户信息，不允许交易！", "017178000001799", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        //DynamicObject obj4 = source.First<DynamicObject>();
                        var obj4 = source.Tables[0].Rows[0];
                        if (Convert.ToString(obj4["FCardStatus"]) != ResManager.LoadKDString("正常", "017178000001738", SubSystemType.RETAIL, new object[0]))
                        {
                            result["Message"] = string.Format(ResManager.LoadKDString("当前卡状态为【{0}】，不允许交易！", "017178000001800", SubSystemType.RETAIL, new object[0]), Convert.ToString(obj4["FCardStatus"]));
                            return result.ToString();
                        }
                        if (Convert.ToString(obj4["FFreezeStatus"]) != ResManager.LoadKDString("正常", "017178000001738", SubSystemType.RETAIL, new object[0]))
                        {
                            result["Message"] = ResManager.LoadKDString("当前卡已冻结，不允许交易！", "017178000001801", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        if ((Convert.ToString(obj4["FValidControl"]) == "1") && ((Convert.ToDateTime(obj4["FDateStart"]) > systemDateTime) || (Convert.ToDateTime(obj4["FDateEnd"]) < systemDateTime)))
                        {
                            result["Message"] = ResManager.LoadKDString("当前卡不在有效期内，不允许交易！", "017178000001802", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        if ((Convert.ToString(obj4["FAcctValidCtrl"]) == "1") && ((Convert.ToDateTime(obj4["FAcctDateStart"]) > systemDateTime) || (Convert.ToDateTime(obj4["FAcctDateEnd"]) < systemDateTime)))
                        {
                            result["Message"] = ResManager.LoadKDString("当前账户不在有效期内，不允许交易！", "017178000001803", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        if ((str6 == "-1") && (num4 > Convert.ToDecimal(obj4["FValue"])))
                        {
                            result["Message"] = ResManager.LoadKDString("当前账户余额不足，不允许交易！", "017178000001804", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        if (!this.CheckCardUseBranch(ctx, num, str, result))
                        {
                            return result.ToString();
                        }
                        long num7 = Convert.ToInt64(obj4["FCardId"]);
                        decimal num8 = Convert.ToDecimal(obj4["FValue"]);
                        decimal num9 = (str6 == "1") ? (num8 + num4 + num5) : (num8 - num4);
                        List<SqlParam> paramList = new List<SqlParam>();

                        //充值-储值账户-正向
                        if (((str4 == "04") && (str5 == "2")) && (str6 == "1"))
                        {
                            string str12 = CommonService.GetJParamString(jParams, "SettleType");
                            //小程序充值收款方式统一按银行处理
                            int num10 = 2;
                            if (!string.IsNullOrWhiteSpace(str12))
                            {
                                num10 = (int)CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_PayMode", "FID", "FNumber", str12, 0L);
                                if (num10 == 0)
                                {
                                    result["Message"] = ResManager.LoadKDString("参数【SettleType：支付方式编码】在系统中不存在！", "017178000001805", SubSystemType.RETAIL, new object[0]);
                                    return result.ToString();
                                }
                            }
                            if ((num3 == 0M) && (num4 > 0M))
                            {
                                num3 = num4;
                            }
                            strSql = "EXEC CMK_PR_POSVIPCardRechargeAppend @UserID, 0, @CardNumber, @CardAccID, @BranchID, @RechargeValue, 0, @SettleAmt, @SettleType, 0, @PresenAmt, @TransSerial, @Note, 0, 0, @FPoint, @FBillNO ";
                            paramList = new List<SqlParam> {
                            new SqlParam("@UserID", KDDbType.Int64, 0),
                            new SqlParam("@CardNumber", KDDbType.String, str),
                            new SqlParam("@CardAccID", KDDbType.Int64, 2),
                            new SqlParam("@BranchID", KDDbType.Int64, num),
                            new SqlParam("@RechargeValue", KDDbType.Decimal, num4),
                            new SqlParam("@SettleAmt", KDDbType.Decimal, num3),
                            new SqlParam("@SettleType", KDDbType.Int64, num10),
                            new SqlParam("@PresenAmt", KDDbType.Decimal, num5),
                            new SqlParam("@FPoint", KDDbType.Decimal, num6),
                            new SqlParam("@TransSerial", KDDbType.String, TransSerial),
                            new SqlParam("@Note", KDDbType.String, str8),
                            new SqlParam("@FBillNO", KDDbType.String, str3),
                            };
                            //DBUtils.Execute(ctx, strSql, paramList);
                            XDDDBUtils.Execute(strSql, paramList);

                            #region 批次处理
                            if (num5 > 0)
                            {
                                //1 插入对应批次表 --本金
                                BatchDataObject bdo = new BatchDataObject();
                                bdo.cardNo = str;  //卡号
                                bdo.rechargeDate = DateTime.Now.ToString("yyyy-MM-dd"); //充值日期
                                bdo.rechargeTime = DateTime.Now.ToString("HH:mm:ss");
                                bdo.rechargeAmt = num4;
                                bdo.giveAmt = num5;
                                bdo.belenceAmt = num4;
                                bdo.AmtType = 0;
                                bdo.Batch = 0L;
                                bdo.BatchType = 0;
                                bdo.BatchUsingStatus = 0;
                                bdo.TransSerial = TransSerial;
                                bdo.Note = str3 + str;
                                BatchHelper.Insert2batch(bdo);
                                //2 插入对应批次表 --赠金
                                BatchDataObject bdo_g = new BatchDataObject();
                                bdo_g.cardNo = str;  //卡号
                                bdo_g.rechargeDate = DateTime.Now.ToString("yyyy-MM-dd"); //充值日期
                                bdo_g.rechargeTime = DateTime.Now.ToString("HH:mm:ss");
                                bdo_g.rechargeAmt = num4;
                                bdo_g.giveAmt = num5;
                                bdo_g.belenceAmt = num5;
                                bdo_g.AmtType = 1;  //金额类型 1-赠金
                                bdo_g.Batch = 0L;
                                bdo_g.BatchType = 0;
                                bdo_g.BatchUsingStatus = 0;
                                bdo_g.TransSerial = TransSerial;
                                bdo_g.Note = str3 + str;
                                BatchHelper.Insert2batch(bdo_g);
                            }
                            else
                            {
                                //插入对应批次表
                                BatchDataObject bdo = new BatchDataObject();
                                bdo.cardNo = str;  //卡号
                                bdo.rechargeDate = DateTime.Now.ToString("yyyy-MM-dd"); //充值日期
                                bdo.rechargeTime = DateTime.Now.ToString("HH:mm:ss");
                                bdo.rechargeAmt = num4;
                                bdo.giveAmt = num5;
                                bdo.belenceAmt = num4;
                                bdo.AmtType = 0;
                                bdo.Batch = 0L;
                                bdo.BatchType = 0;
                                bdo.BatchUsingStatus = 0;
                                bdo.TransSerial = TransSerial;
                                bdo.Note = str3 + str;
                                BatchHelper.Insert2batch(bdo);
                            }
                            #endregion
                        }
                        else
                        {
                            //控制金额调整的交易序列号唯一
                            if (!CommonService.getTransSerial(ctx, str, TransSerial))
                            {
                                strSql = "UPDATE CMK_T_VIP_CARDACCTS SET FValue = @BalValue WHERE FCardId = @FCardId AND FACCOUNTID = @CardAccID ";
                                paramList = new List<SqlParam> {
                                new SqlParam("@FCardId", KDDbType.Int64, num7),
                                new SqlParam("@CardAccID", KDDbType.Int64, str5),
                                new SqlParam("@BalValue", KDDbType.Decimal, num9)};
                                //DBUtils.Execute(ctx, strSql, paramList);
                                XDDDBUtils.Execute(strSql, paramList);
                                if (((str5 == "1") && (str6 == "1")) && (num4 > 0M))
                                {
                                    strSql = "UPDATE CMK_T_VIP_CARD SET FSumPoints = FSumPoints + @Value WHERE FCardId = @FCardId ";
                                    paramList = new List<SqlParam> {
                                    new SqlParam("@FCardId", KDDbType.Int64, num7),
                                    new SqlParam("@Value", KDDbType.Decimal, num4)};
                                    //DBUtils.Execute(ctx, strSql, paramList);
                                    XDDDBUtils.Execute(strSql, paramList);
                                }
                                //插入卡金额调整单  卡金额调整单分类--交易扣款  交易退款  充值退款



                                //List<long> list2 = DBServiceHelper.GetSequenceInt64(ctx, "CMK_VIP_T_CardAction", 1).ToList<long>();
                                long FID = 0L;
                                strSql = "EXEC CMK_PR_GetTableSequence @TableName = 'CMK_VIP_T_CardAction', @Count =  1";
                                var Idrs = XDDDBUtils.ExecuteDateSet(strSql);
                                if (Idrs != null && Idrs.Tables.Count > 0 && Idrs.Tables[0].Rows.Count > 0)
                                {
                                    FID = Convert.ToInt64(Idrs.Tables[0].Rows[0]["Id"]);
                                }

                                strSql = @"INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBRANCHID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, 
                                FRECORDDATETIME, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL)
                                SELECT @FID, 'CMK_VIP_CardActionFlow', 0, @FBillNO, @FBIZTYPE, @OrgID, @BranchID, FCardID, FVIPMEMBERID, @CardAccID, @FOption, @OperValue, @BalValue, 
                                @Date, @Date, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, '', @OperType, @UserID, 0, @Note, @TransSerial  
                                FROM CMK_T_VIP_CARD WHERE FCardID = @FCardID ";
                                paramList = new List<SqlParam> {
                                new SqlParam("@FID", KDDbType.Int64, FID),
                                new SqlParam("@FCardId", KDDbType.Int64, num7),
                                new SqlParam("@CardAccID", KDDbType.Int64, str5),
                                new SqlParam("@UserID", KDDbType.Int64, 0),
                                new SqlParam("@OrgID", KDDbType.Int64, iD),
                                new SqlParam("@BranchID", KDDbType.Int64, num),
                                new SqlParam("@FOption", KDDbType.String, str6),
                                new SqlParam("@OperValue", KDDbType.Decimal, num4),
                                new SqlParam("@BalValue", KDDbType.Decimal, num9),
                                new SqlParam("@OperType", KDDbType.String, str4),
                                new SqlParam("@Date", KDDbType.DateTime, systemDateTime),
                                new SqlParam("@FBillNO", KDDbType.String, str3),
                                new SqlParam("@FBIZTYPE", KDDbType.String, str4 == "08"? "CMK_VIP_ChangeAmount":""),
                                new SqlParam("@Note", KDDbType.String, str8),
                                new SqlParam("@TransSerial", KDDbType.String, TransSerial)};
                                //DBUtils.Execute(ctx, strSql, paramList);
                                XDDDBUtils.Execute(strSql, paramList);

                                #region 批次处理
                                if (str6 == "-1")
                                {
                                    //消费扣减批次记录
                                    BatchHelper.Reduce2batch(str, num4, TransSerial, 1);
                                }
                                else
                                {
                                    string RTransSerial = CommonService.GetJParamString(jParams, "RTransSerial");
                                    if (!string.IsNullOrWhiteSpace(RTransSerial))
                                    {
                                        //退货 --查询退货对应的消费批次扣除记录 获取本金 赠金   卡流水表查询 本金发生额：FCapitalOperValue    赠金发生额：FGrantOperValue 
                                        decimal FCapitalOperValue = 0M;
                                        decimal FGrantOperValue = 0M;
                                        BatchHelper.getAmtByTransSerial(RTransSerial, num4, out FCapitalOperValue, out FGrantOperValue);
                                        //若本次退款扣减的批次有赠送，记录新增两个批次      区分部分退款（部分退款优先退还赠金  然后退还本金）
                                        if (FCapitalOperValue > 0M && FGrantOperValue > 0M)
                                        {
                                            //1 插入对应批次表 --本金
                                            BatchDataObject bdo = new BatchDataObject();
                                            bdo.cardNo = str;  //卡号
                                            bdo.rechargeDate = DateTime.Now.ToString("yyyy-MM-dd"); //退款日期
                                            bdo.rechargeTime = DateTime.Now.ToString("HH:mm:ss");
                                            bdo.rechargeAmt = 0M;
                                            bdo.giveAmt = 0M;
                                            bdo.belenceAmt = FCapitalOperValue;
                                            bdo.AmtType = 0;
                                            bdo.Batch = 0L;
                                            bdo.BatchType = 1;
                                            bdo.BatchUsingStatus = 0;
                                            bdo.TransSerial = TransSerial;
                                            bdo.Note = str3 + str;
                                            BatchHelper.Insert2batch(bdo);
                                            //2 插入对应批次表 --赠金
                                            BatchDataObject bdo_g = new BatchDataObject();
                                            bdo_g.cardNo = str;  //卡号
                                            bdo_g.rechargeDate = DateTime.Now.ToString("yyyy-MM-dd"); //退款日期
                                            bdo_g.rechargeTime = DateTime.Now.ToString("HH:mm:ss");
                                            bdo_g.rechargeAmt = 0M;
                                            bdo_g.giveAmt = 0M;
                                            bdo_g.belenceAmt = FGrantOperValue;
                                            bdo_g.AmtType = 1;  //金额类型 1-赠金
                                            bdo_g.Batch = 0L;
                                            bdo_g.BatchType = 1;
                                            bdo_g.BatchUsingStatus = 0;
                                            bdo_g.TransSerial = TransSerial;
                                            bdo_g.Note = str3 + str;
                                            BatchHelper.Insert2batch(bdo_g);
                                        }
                                        else if (FCapitalOperValue > 0M && FGrantOperValue == 0M)
                                        {
                                            //插入对应批次表
                                            BatchDataObject bdo = new BatchDataObject();
                                            bdo.cardNo = str;  //卡号
                                            bdo.rechargeDate = DateTime.Now.ToString("yyyy-MM-dd"); //退货日期
                                            bdo.rechargeTime = DateTime.Now.ToString("HH:mm:ss");
                                            bdo.rechargeAmt = 0M;
                                            bdo.giveAmt = 0M;
                                            bdo.belenceAmt = FCapitalOperValue;
                                            bdo.AmtType = 0;
                                            bdo.Batch = 0L;
                                            bdo.BatchType = 1;
                                            bdo.BatchUsingStatus = 0;
                                            bdo.TransSerial = TransSerial;
                                            bdo.Note = str3 + str;
                                            BatchHelper.Insert2batch(bdo);
                                        }
                                        else if (FCapitalOperValue == 0M && FGrantOperValue > 0M)
                                        {
                                            BatchDataObject bdo_g = new BatchDataObject();
                                            bdo_g.cardNo = str;  //卡号
                                            bdo_g.rechargeDate = DateTime.Now.ToString("yyyy-MM-dd"); //退货日期
                                            bdo_g.rechargeTime = DateTime.Now.ToString("HH:mm:ss");
                                            bdo_g.rechargeAmt = 0M;
                                            bdo_g.giveAmt = 0M;
                                            bdo_g.belenceAmt = FGrantOperValue;
                                            bdo_g.AmtType = 1;  //金额类型 1-赠金
                                            bdo_g.Batch = 0L;
                                            bdo_g.BatchType = 1;
                                            bdo_g.BatchUsingStatus = 0;
                                            bdo_g.TransSerial = TransSerial;
                                            bdo_g.Note = str3 + str;
                                            BatchHelper.Insert2batch(bdo_g);
                                        }
                                    }
                                }
                                #endregion
                            }
                            else
                            {
                                result["Message"] = ResManager.LoadKDString("交易失败，原因：本次消费操作已经完成，不允许重复提交！", "017178000001806", SubSystemType.RETAIL, new object[0]);
                                return result.ToString();
                            }
                        }
                        JObject item = new JObject {
                        {
                            "AccountId",
                            str5
                        },
                        {
                            "OldValue",
                            Convert.ToInt32(num8 * 100)
                        },
                        {
                            "BalValue",
                            Convert.ToInt32(num9 * 100)
                        }
                    };
                        array2.Add(item);
                    }
                    scope.Complete();
                }
                result["Result"] = true;
                result["Code"] = 1;
                result["Message"] = ResManager.LoadKDString("交易成功", "017178000001806", SubSystemType.RETAIL, new object[0]);
                result["Data"] = array2;
            }
            catch (Exception exception)
            {
                result["Result"] = false;
                result["Message"] = string.Format(ResManager.LoadKDString("交易失败，原因：{0}", "017178000001807", SubSystemType.RETAIL, new object[0]), exception.Message);
            }
            return result.ToString();
        }
        #endregion

        #region 卡账户交易冲正New
        internal string CardAcctTransActionUndo(Context ctx, string strParams, string TransSerial, JObject result)
        {
            try
            {
                string str = "";
                string str2 = "";
                string jParamString = "";
                result["Result"] = false;
                JObject jParams = JObject.Parse(strParams);
                DateTime systemDateTime = DateTime.Now; //ServiceFactory.GetTimeService(ctx).GetSystemDateTime(ctx);
                jParamString = CommonService.GetJParamString(jParams, "BranchNumber");
                if (string.IsNullOrWhiteSpace(jParamString))
                {
                    result["Message"] = ResManager.LoadKDString("参数【BranchNumber：门店编码】未设置！", "017178000000462", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                long num = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", jParamString, 0L);
                if (num == 0L)
                {
                    result["Message"] = ResManager.LoadKDString("参数【BranchNumber：门店编码】在系统中不存在！", "017178000000452", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                str = CommonService.GetJParamString(jParams, "CardNo");
                if (string.IsNullOrWhiteSpace(str))
                {
                    result["Message"] = ResManager.LoadKDString("参数【CardNo：卡号】未设置！", "017178000001782", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                JArray array = jParams["dataAccts"] as JArray;
                if ((array == null) || (array.Count == 0))
                {
                    result["Message"] = ResManager.LoadKDString("参数【dataAccts：卡账户数据包】未设置！", "017178000001793", SubSystemType.RETAIL, new object[0]);
                    return result.ToString();
                }
                JArray array2 = new JArray();
                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    foreach (JObject obj3 in (IEnumerable<JToken>)array)
                    {
                        str2 = CommonService.GetJParamString(obj3, "AccountId");
                        if (string.IsNullOrWhiteSpace(str2))
                        {
                            result["Message"] = ResManager.LoadKDString("参数【AccountId：卡账户】未设置！", "017178000001794", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        string strSQL = string.Format("SELECT TOP 1 t1.FCardId, t2.FValue FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDACCTS t2 ON t1.FCardId = t2.FCardId WHERE t1.FNumber = '{0}' AND t2.FAccountId = {1}",
                           str, str2);
                        //DynamicObjectCollection source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                        DataSet source = XDDDBUtils.ExecuteDateSet(strSQL);
                        if ((source == null) || (source.Tables[0].Rows.Count == 0))
                        {
                            result["Message"] = ResManager.LoadKDString("未找到对应的卡号和卡账户信息，交易冲正失败！", "017178000001808", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        //DynamicObject obj4 = source.First<DynamicObject>();
                        var obj4 = source.Tables[0].Rows[0];

                        long num2 = Convert.ToInt64(obj4["FCardId"]);
                        decimal num3 = Convert.ToDecimal(obj4["FValue"]);
                        strSQL = string.Format("SELECT TOP 1 FOPTION, FOPERVALUE, FOPERATIONTYPE FROM CMK_VIP_T_CardAction WHERE FCardID = {0} AND FACCOUNTID = {1} AND FTRANSSERIAL = '{2}' ", num2, str2, TransSerial);
                        //DynamicObjectCollection objects2 = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                        DataSet objects2 = XDDDBUtils.ExecuteDateSet(strSQL);
                        if ((objects2 == null) || (objects2.Tables[0].Rows.Count == 0))
                        {
                            result["Message"] = ResManager.LoadKDString("未找到交易序列号对应的数据记录，交易冲正失败！", "017178000001809", SubSystemType.RETAIL, new object[0]);
                            return result.ToString();
                        }
                        //DynamicObject obj5 = objects2.First<DynamicObject>();
                        var obj5 = objects2.Tables[0].Rows[0];
                        string str5 = Convert.ToString(obj5["FOPTION"]);
                        string str6 = Convert.ToString(obj5["FOPERATIONTYPE"]);
                        decimal num4 = Convert.ToDecimal(obj5["FOPERVALUE"]);
                        decimal num5 = (str5 == "1") ? (num3 - num4) : (num3 + num4);
                        decimal num6 = 0M;
                        decimal.TryParse(CommonService.GetJParamString(obj3, "FGiveAmount"), out num6);
                        decimal num7 = 0M;
                        decimal.TryParse(CommonService.GetJParamString(obj3, "FGivePoint"), out num7);
                        List<SqlParam> paramList = new List<SqlParam>();
                        //根据序列号查找对应的充值单进行冲正
                        if (((str6 == "04") && (str2 == "2")) && (str5 == "1"))
                        {
                            strSQL = "EXEC CMK_PR_POSVIPCardRechargeUndo @UserID, 0, @CardNumber, @CardAccID, @BranchID, @RechargeValue, 0, @RechargeValue, 2, 0, @PresenAmt, @TransSerial, @Note, 0, '', 0, @FPoint ";
                            paramList = new List<SqlParam>{
                            new SqlParam("@UserID", KDDbType.Int64, 0),
                            new SqlParam("@CardNumber", KDDbType.String, str),
                            new SqlParam("@CardAccID", KDDbType.Int64, 2),
                            new SqlParam("@BranchID", KDDbType.Int64, num),
                            new SqlParam("@RechargeValue", KDDbType.Decimal, num4),
                            new SqlParam("@PresenAmt", KDDbType.Decimal, num6),
                            new SqlParam("@FPoint", KDDbType.Decimal, num7),
                            new SqlParam("@TransSerial", KDDbType.String, TransSerial),
                            new SqlParam("@Note", KDDbType.String, ResManager.LoadKDString("卡账户交易冲正", "017178000001810", SubSystemType.RETAIL, new object[0]))};
                            //DBUtils.Execute(ctx, strSQL, paramList);
                            XDDDBUtils.Execute(strSQL, paramList);

                            //充值冲正--根据交易序列号把批次标记作废
                            string sql = string.Format("", TransSerial);



                        }
                        else
                        {
                            //把流水记录里记录的扣减冲回去


                            strSQL = "UPDATE CMK_T_VIP_CARDACCTS SET FValue = @BalValue WHERE FCardId = @FCardId AND FACCOUNTID = @CardAccID ";
                            paramList = new List<SqlParam> {
                            new SqlParam("@FCardId", KDDbType.Int64, num2),
                            new SqlParam("@CardAccID", KDDbType.Int64, str2),
                            new SqlParam("@BalValue", KDDbType.Decimal, num5)};
                            //DBUtils.Execute(ctx, strSQL, paramList);
                            XDDDBUtils.Execute(strSQL, paramList);
                            if (((str2 == "1") && (str5 == "1")) && (num4 > 0M))
                            {
                                strSQL = "UPDATE CMK_T_VIP_CARD SET FSumPoints = FSumPoints - @Value WHERE FCardId = @FCardId ";
                                paramList = new List<SqlParam> {
                                new SqlParam("@FCardId", KDDbType.Int64, num2),
                                new SqlParam("@Value", KDDbType.Decimal, num4)
                            };
                                //DBUtils.Execute(ctx, strSQL, paramList);
                                XDDDBUtils.Execute(strSQL, paramList);
                            }
                            strSQL = @"INSERT INTO CMK_VIP_T_CardActUndoBK(FID,FFORMID,FBILLNO,FBIZTYPE,FCARDID,FACCOUNTID,FORGID,FCHANNELID,FBIZDATE,FRECORDDATETIME,FPOSID,FOPTION,FOPERVALUE,FBALANCE,FNOTE,FOPERATIONTYPE,FCARDSTATUS,FFREEZESTATUS,FOPERATORID,FTRANSSERIAL,FCONSUMESTATUS)                          
                            SELECT FID,FFORMID,FBILLNO,FBIZTYPE,FCARDID,FACCOUNTID,FORGID,FCHANNELID,FBIZDATE,FRECORDDATETIME,FPOSID,FOPTION,FOPERVALUE,FBALANCE,FNOTE,FOPERATIONTYPE,FCARDSTATUS,FFREEZESTATUS,FOPERATORID,FTRANSSERIAL,FCONSUMESTATUS                           
                            FROM CMK_VIP_T_CardAction WHERE FCardID = @FCardID AND FACCOUNTID = @CardAccID AND FTRANSSERIAL = @TransSerial                           
                            INSERT INTO CMK_VIP_T_CardActUndo(FID,FBILLNO,FBIZTYPE,FCARDID,FACCOUNTID,FORGID,FCHANNELID,FCARDLEVELID,FBIZDATE,FRECORDDATETIME,FPOSID,FBEFOREBALANCE,FOPTION,FOPERVALUE,FBALANCE,FNOTE,FOPERATIONTYPE,FBILLID,FMEMBERID,FOPERATORID,FMATERIALID,FTRANSSERIAL)                         
                            SELECT FID,FBILLNO,FBIZTYPE,FCARDID,FACCOUNTID, FORGID, FBRANCHID, FCARDLEVELID,@Date,@Date,0,FBALANCE, FOPTION, FOPERVALUE, FBALANCE-FOPTION*FOPERVALUE, @Note, FOPERATIONTYPE,FBILLID,FMEMBERID,@UserID,FMATERIALID,FTRANSSERIAL                          
                            FROM CMK_VIP_T_CardAction WHERE FCardID = @FCardID AND FACCOUNTID = @CardAccID AND FTRANSSERIAL = @TransSerial                               
                            DELETE CMK_VIP_T_CardAction WHERE FCardID = @FCardID AND FACCOUNTID = @CardAccID AND FTRANSSERIAL = @TransSerial ";
                            paramList = new List<SqlParam> {
                            new SqlParam("@FCardId", KDDbType.Int64, num2),
                            new SqlParam("@CardAccID", KDDbType.Int64, str2),
                            new SqlParam("@UserID", KDDbType.Int64, 0),
                            new SqlParam("@Date", KDDbType.DateTime, systemDateTime),
                            new SqlParam("@TransSerial", KDDbType.String, TransSerial),
                            new SqlParam("@Note", KDDbType.String, ResManager.LoadKDString("卡账户交易冲正", "017178000001810", SubSystemType.RETAIL, new object[0]))};
                            //DBUtils.Execute(ctx, strSQL, paramList);
                            XDDDBUtils.Execute(strSQL, paramList);


                        }
                        JObject item = new JObject {
                        {
                            "AccountId",
                            str2
                        },
                        {
                            "OldValue",
                            Convert.ToInt32(num3 * 100)
                        },
                        {
                            "BalValue",
                            Convert.ToInt32(num5 * 100)
                        }
                    };
                        array2.Add(item);
                    }
                    scope.Complete();
                }
                result["Result"] = true;
                result["Code"] = 1;
                result["Message"] = ResManager.LoadKDString("交易冲正成功", "017178000001811", SubSystemType.RETAIL, new object[0]);
                result["Data"] = array2;
            }
            catch (Exception exception)
            {
                result["Result"] = false;
                result["Message"] = string.Format(ResManager.LoadKDString("交易冲正失败，原因：{0}", "017178000001812", SubSystemType.RETAIL, new object[0]), exception.Message);
            }
            return result.ToString();
        }
        #endregion

        #region 礼券信息查询
        internal string QueryTicketInfo(Context ctx, string BranchNumber, string TicketNo, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();

                long lBranchId = 0;
                if (!string.IsNullOrEmpty(BranchNumber))
                {
                    lBranchId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", BranchNumber);
                }

                sbSql.AppendLine("SELECT FTicketNo,FTicketNumber,FTicketType, FTicketValue, FSaleAmount, FBeginDate, FEndDate, FConsumeRule, FUseRule, FTicketStatusCode, FTicketStatus FROM ");
                sbSql.AppendLine("(SELECT DISTINCT t2.FTicketNo,type.FNumber FTicketNumber,ISNULL(t3.FNAME, '') AS FTicketType, t2.FTicketValue, t2.FSaleAmount, CONVERT(varchar(100), t2.FBeginDate, 23) AS FBeginDate, CONVERT(varchar(100), t2.FEndDate, 23) AS FEndDate, ");
                sbSql.AppendLine("    CASE WHEN t2.FCONSUMEAMT > 0 THEN CONCAT(CONCAT('单笔消费金额满', CONVERT(VARCHAR, CONVERT(DECIMAL(20, 2), t2.FCONSUMEAMT))), '元使用') ELSE '不限消费金额' END AS FConsumeRule,  ");
                sbSql.AppendLine("    CASE t2.FCONDITION WHEN '0' THEN '每单限使用一张' WHEN '1' THEN '根据消费金额累加' ELSE '不限使用张数' END AS FUseRule, t2.FTicketStatus AS FTicketStatusCode, ");
                sbSql.AppendLine("    CASE t2.FTicketStatus WHEN 'A' THEN '已发行' WHEN 'C' THEN '已消费' WHEN 'B' THEN '已回收' WHEN 'O' THEN '已过期' ELSE '未发行' END AS FTicketStatus ");
                sbSql.AppendLine("    FROM CMK_RT_TicketsInfo t2 INNER JOIN CMK_RT_TicketsType_L t3 ON t2.FTICKETTYPE = t3.FID AND t3.FLocaleId = @FLocaleId ");
                sbSql.AppendLine("    INNER JOIN CMK_RT_TicketsType type ON type.FID = t2.FTICKETTYPE ");
                if (lBranchId > 0)
                {
                    sbSql.AppendLine("    LEFT JOIN CMK_RT_TicketsType t5 ON t2.FTICKETTYPE = t5.FID ");
                }
                //返回所有状态的券
                sbSql.AppendLine("WHERE t2.FTicketStatus IN ('A', 'C', 'B', 'O','E') AND t2.FTicketNo = @TicketNo ");

                if (lBranchId > 0)
                {
                    sbSql.AppendLine(@"    AND (t5.FBRANCHCONTROL = '0' OR (t5.FBRANCHCONTROL = '1' AND t2.FGETBRANCHID = @BranchId) 
                        OR (t5.FBRANCHCONTROL = '2' AND EXISTS(SELECT TOP 1 1 FROM CMK_RT_TicketsTypeBranch WHERE FID = t2.FTICKETTYPE AND FBranchID = @BranchId AND FISSELECTED = '1')) ) ");
                    lstParam.Add(new SqlParam("@BranchId", KDDbType.Int64, lBranchId));
                }

                sbSql.AppendLine(" ) t ");

                lstParam.Add(new SqlParam("@TicketNo", KDDbType.String, TicketNo));
                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, "2052"));



                //通过上下文获取
                //var Datas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                //if (Datas != null && Datas.Count > 0)
                //{
                //    result["Result"] = true;
                //    result["Message"] = "礼券信息查询查询成功";
                //    result["Data"] = JArray.FromObject(Datas);
                //}
                //else
                //{
                //    result["Result"] = true;
                //    result["Message"] = "礼券信息查询完成，返回查询结果为空！";
                //}
                //通过数据库直连获取
                DataSet ds = Data.XDDDBUtils.ExecuteDateSet(sbSql.ToString(), lstParam);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "礼券信息查询查询成功";
                    result["Data"] = JArray.FromObject(ds.Tables[0]); //JArray.Parse(CommonService.ToJson(ds).Replace("\\",""));
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "礼券信息查询完成，返回查询结果为空！";
                }

            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("礼券信息查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 礼券查询（会员持券）
        internal string QueryVIPTickets(Context ctx, string CardNo, string MobileNo, string BranchNumber, string TickStatus, JObject result)
        {
            try
            {
                result["Result"] = false;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();

                //long lBranchId = 0;
                //if (!string.IsNullOrWhiteSpace(BranchNumber))
                //{
                //    lBranchId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", BranchNumber);
                //}

                sbSql.AppendLine("SELECT FTicketNo, FTicketNumber,FTicketType, FTicketValue, FSaleAmount, FBeginDate, FEndDate, FConsumeRule, FUseRule, FTicketStatusCode, FTicketStatus FROM ");
                sbSql.AppendLine("(SELECT TOP 200 t2.FTicketNo,type.FNUMBER FTicketNumber, ISNULL(t3.FNAME, '') AS FTicketType, t2.FTicketValue, t2.FSaleAmount, CONVERT(varchar(100), t2.FBeginDate, 23) AS FBeginDate, CONVERT(varchar(100), t2.FEndDate, 23) AS FEndDate, ");
                sbSql.AppendLine("    CASE WHEN t2.FCONSUMEAMT > 0 THEN CONCAT(CONCAT('单笔消费金额满', CONVERT(VARCHAR, CONVERT(DECIMAL(20, 2), t2.FCONSUMEAMT))), '元使用') ELSE '不限消费金额' END AS FConsumeRule,  ");
                sbSql.AppendLine("    CASE t2.FCONDITION WHEN '0' THEN '每单限使用一张' WHEN '1' THEN '根据消费金额累加' ELSE '不限使用张数' END AS FUseRule, t2.FTicketStatus AS FTicketStatusCode, ");
                sbSql.AppendLine("    CASE t2.FTicketStatus WHEN 'A' THEN '已发行' WHEN 'C' THEN '已消费' WHEN 'B' THEN '已回收' WHEN 'O' THEN '已过期' ELSE '未发行' END AS FTicketStatus ");
                sbSql.AppendLine("FROM CMK_T_VIP_Member t1 INNER JOIN CMK_RT_TicketsInfo t2 ON t1.FVIPID = t2.FVIPID ");
                sbSql.AppendLine("    INNER JOIN CMK_RT_TicketsType type ON type.FID = t2.FTICKETTYPE ");
                sbSql.AppendLine("    INNER JOIN CMK_RT_TicketsType_L t3 ON t3.FID = type.FID AND t3.FLocaleId = @FLocaleId ");

                if (!string.IsNullOrWhiteSpace(CardNo))
                {
                    sbSql.AppendLine("    LEFT JOIN CMK_T_VIP_CARD t4 ON t4.FVIPMemberID = t1.FVIPID ");
                }

                //if (lBranchId > 0)
                //{
                //    sbSql.AppendLine("    LEFT JOIN CMK_RT_TicketsType t5 ON t2.FTICKETTYPE = t5.FID ");
                //}

                sbSql.AppendLine("WHERE 1 = 1 ");

                if (!string.IsNullOrWhiteSpace(CardNo))
                {
                    sbSql.AppendLine(" AND t4.FNumber = @CardNo ");
                    lstParam.Add(new SqlParam("@CardNo", KDDbType.String, CardNo));
                }

                if (!string.IsNullOrWhiteSpace(MobileNo))
                {
                    sbSql.AppendLine(" AND t1.FMobile = @MobileNo ");
                    lstParam.Add(new SqlParam("@MobileNo", KDDbType.String, MobileNo));
                }

                //if (lBranchId > 0)
                //{
                //    sbSql.AppendLine(@"    AND (t5.FBRANCHCONTROL = '0' OR (t5.FBRANCHCONTROL = '1' AND t2.FGETBRANCHID = @BranchId) 
                //        OR (t5.FBRANCHCONTROL = '2' AND EXISTS(SELECT TOP 1 1 FROM CMK_RT_TicketsTypeBranch WHERE FID = t2.FTICKETTYPE AND FBranchID = @BranchId AND FISSELECTED = '1' ) ) ) ");
                //    lstParam.Add(new SqlParam("@BranchId", KDDbType.Int64, lBranchId));
                //}

                if (!string.IsNullOrWhiteSpace(TickStatus))
                {
                    sbSql.AppendLine(" AND t2.FTicketStatus = @Status ");
                    lstParam.Add(new SqlParam("@Status", KDDbType.String, TickStatus));
                }

                sbSql.AppendLine(") t ");

                lstParam.Add(new SqlParam("@FLocaleId", KDDbType.Int32, "2052"));

                //通过上下文查询获取
                //DynamicObjectCollection Datas = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                //if (Datas != null && Datas.Count > 0)
                //{
                //    result["Result"] = true;
                //    result["Message"] = "会员持券查询成功";
                //    result["Data"] = JArray.FromObject(Datas);
                //}
                //else
                //{
                //    result["Result"] = true;
                //    result["Message"] = "会员持券查询完成，返回查询结果为空！";
                //}
                //通过数据库直连查询获取
                DataSet ds = Data.XDDDBUtils.ExecuteDateSet(sbSql.ToString(), lstParam);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "会员持券查询成功";
                    result["Data"] = JArray.FromObject(ds.Tables[0]);  //JArray.Parse(CommonService.ToJson(ds).Replace("\\", ""));
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "会员持券查询完成，返回查询结果为空！";
                }


            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("会员持券查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 礼券派发方案查询（会员领券）
        internal string QueryVIPTicketScheme(Context ctx, string CardNo, string MobileNo, int iPageSize, int iPageNum, JObject result)
        {
            try
            {
                result["Result"] = false;
                long lVipId = 0;
                StringBuilder sbSql = new StringBuilder();
                List<SqlParam> lstParam = new List<SqlParam>();

                if (!string.IsNullOrWhiteSpace(CardNo) || !string.IsNullOrWhiteSpace(MobileNo))
                {
                    sbSql.AppendLine("SELECT TOP 1 t1.FVIPID FROM CMK_T_VIP_Member t1 LEFT JOIN CMK_T_VIP_CARD t2 ON t2.FVIPMemberID = t1.FVIPID WHERE 1 = 1 ");

                    if (!string.IsNullOrWhiteSpace(CardNo))
                    {
                        sbSql.AppendLine(" AND t2.FNumber = @CardNo ");
                        lstParam.Add(new SqlParam("@CardNo", KDDbType.String, CardNo));
                    }

                    if (!string.IsNullOrWhiteSpace(MobileNo))
                    {
                        sbSql.AppendLine(" AND t1.FMobile = @MobileNo ");
                        lstParam.Add(new SqlParam("@MobileNo", KDDbType.String, MobileNo));
                    }
                    var vips = DBUtils.ExecuteDynamicObject(ctx, sbSql.ToString(), null, null, CommandType.Text, lstParam.ToArray());
                    if (vips == null || vips.Count == 0)
                    {
                        result["Message"] = "查询不到对应会员";
                        return result.ToString();
                    }

                    lVipId = Convert.ToInt64(vips.First()["FVIPID"]);
                }

                lstParam = new List<SqlParam>();
                string strSql = @"EXEC CMK_PR_GetRushTicketsData @VipId ";
                lstParam.Add(new SqlParam("@VipId", KDDbType.String, lVipId));
                var TotalDatas = DBUtils.ExecuteDynamicObject(ctx, strSql, null, null, CommandType.Text, lstParam.ToArray());
                if (TotalDatas != null && TotalDatas.Count > 0)
                {
                    int Seq = 1;
                    int iBNum = 1;
                    int iENum = 10;
                    int TotalPage = 0;
                    int TotalCount = TotalDatas.Count;

                    iPageSize = iPageSize <= 0 ? TotalDatas.Count : iPageSize;
                    TotalPage = (int)Math.Ceiling(Convert.ToDecimal(TotalCount) / iPageSize);
                    iPageNum = iPageNum <= 0 ? 1 : iPageNum;
                    iPageNum = iPageNum > TotalPage ? TotalPage : iPageNum;

                    iBNum = iPageSize * (iPageNum - 1) + 1;
                    iENum = iPageSize * (iPageNum);

                    JObject Data = new JObject();
                    Data.Add("TotalCount", TotalCount);
                    Data.Add("PageSize", iPageSize);
                    Data.Add("TotalPage", TotalPage);
                    Data.Add("CurPage", iPageNum);

                    JArray Datas = new JArray();
                    foreach (var Item in TotalDatas)
                    {
                        if (Seq >= iBNum && Seq <= iENum)
                        {
                            Seq++;
                            Datas.Add(JObject.FromObject(Item));
                        }
                    }

                    if (Datas != null && Datas.Count > 0)
                    {
                        Data.Add("Datas", Datas);

                        result["Result"] = true;
                        result["Message"] = "礼券方案查询成功";
                        result["Data"] = Data;
                    }
                    else
                    {
                        result["Result"] = true;
                        result["Message"] = "礼券方案查询完成，当前页没有数据！";
                    }
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "礼券方案查询完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("礼券方案查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 礼券领取（会员领券购券）
        internal string VIPTicketSchemeAction(Context ctx, string strParams, JObject result)
        {
            try
            {
                string VIPNumber = "";        //会员编号
                string SchemeId = "";         //派发方案ID
                string SettleAmt = "";        //购券金额
                string SettleType = "";       //支付方式编码

                result["Result"] = false;
                JObject jParams = JObject.Parse(strParams);

                VIPNumber = CommonService.GetJParamString(jParams, "VIPNumber");
                if (string.IsNullOrWhiteSpace(VIPNumber))
                {
                    result["Message"] = "参数【VIPNumber：会员编号】未设置！";
                    return result.ToString();
                }

                SchemeId = CommonService.GetJParamString(jParams, "SchemeId");
                if (string.IsNullOrWhiteSpace(SchemeId))
                {
                    result["Message"] = "参数【SchemeId：派发方案ID】未设置！";
                    return result.ToString();
                }

                decimal dSettleAmt = 0M;
                SettleAmt = CommonService.GetJParamString(jParams, "SettleAmt");
                if (!decimal.TryParse(SettleAmt, out dSettleAmt) || dSettleAmt < 0M)
                {
                    result["Message"] = "参数【SettleAmt：售券金额】设置错误！";
                    return result.ToString();
                }

                long lSettleId = 0;
                if (dSettleAmt > 0)
                {
                    SettleType = CommonService.GetJParamString(jParams, "SettleType");
                    if (string.IsNullOrWhiteSpace(SettleType))
                    {
                        result["Message"] = "参数【SettleType：支付方式编码】未设置！";
                        return result.ToString();
                    }

                    lSettleId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_PayMode", "FID", "FNumber", SettleType);
                    if (lSettleId == 0)
                    {
                        result["Message"] = "参数【SettleType：支付方式编码】在系统中不存在！";
                        return result.ToString();
                    }
                }

                long lVipId = CommonService.GetBaseDataIdByValue(ctx, "CMK_T_VIP_Member", "FVIPID", "FNumber", VIPNumber);
                if (lVipId == 0)
                {
                    result["Message"] = "查询不到对应会员";
                    return result.ToString();
                }

                using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                {
                    List<SqlParam> lstParam = new List<SqlParam>();
                    string strSql = @"EXEC CMK_PR_NewVIPSendTicket @VipId, @SchemeId, '4', @SettleAmt, @SettleType ";
                    lstParam.Add(new SqlParam("@VipId", KDDbType.String, lVipId));
                    lstParam.Add(new SqlParam("@SchemeId", KDDbType.String, SchemeId));
                    lstParam.Add(new SqlParam("@SettleAmt", KDDbType.Decimal, dSettleAmt));
                    lstParam.Add(new SqlParam("@SettleType", KDDbType.Int32, lSettleId));
                    var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql, null, null, CommandType.Text, lstParam.ToArray());
                    if (Datas != null && Datas.Count > 0)
                    {
                        var Data = Datas.First();
                        string strErrMsg = Convert.ToString(Data["ErrMsg"]);
                        if (!string.IsNullOrWhiteSpace(strErrMsg))
                        {
                            result["Message"] = string.Format("礼券领取失败：{0} ", strErrMsg);
                            return result.ToString();
                        }

                        scope.Complete();

                        result["Result"] = true;
                        result["Message"] = "礼券领取成功";

                        JObject data = new JObject();
                        data.Add("FTicketNo", Convert.ToString(Datas.First()["FTicketNo"]));
                        result["Data"] = data;
                    }
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("礼券领取失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 礼券发售
        internal string TicketPublish(Context ctx, string strParams, string TransSerial, JObject result)
        {
            try
            {
                string BranchNumber = "";     //门店编码
                string VIPNumber = "";        //会员编号
                string TicketNo = "";         //礼券编号
                string SaleAmt = "";          //售券金额
                string SettleAmt = "";        //付款金额
                string SettleType = "";       //支付方式编码
                string BillNo = "";           //单据编号
                string Note = "";             //备注
                string ticketStatus = "";     //礼券状态

                result["Result"] = false;
                JObject jParams = JObject.Parse(strParams);

                BranchNumber = CommonService.GetJParamString(jParams, "BranchNumber");
                if (string.IsNullOrWhiteSpace(BranchNumber))
                {
                    result["Message"] = "参数【BranchNumber：门店编码】未设置！";
                    return result.ToString();
                }

                long lBranchId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", BranchNumber);
                if (lBranchId == 0)
                {
                    result["Message"] = "参数【BranchNumber：门店编码】在系统中不存在！";
                    return result.ToString();
                }

                BillNo = CommonService.GetJParamString(jParams, "BillNo");
                if (string.IsNullOrWhiteSpace(BillNo))
                {
                    result["Message"] = "参数【BillNo：单据编号】未设置！";
                    return result.ToString();
                }

                Note = CommonService.GetJParamString(jParams, "Note");
                if (string.IsNullOrWhiteSpace(Note))
                {
                    Note = "线上礼券发售接口调用生成";
                }

                TicketNo = CommonService.GetJParamString(jParams, "TicketNo");
                if (string.IsNullOrWhiteSpace(TicketNo))
                {
                    result["Message"] = "参数【TicketNo：礼券编号】未设置！";
                    return result.ToString();
                }

                decimal dSaleAmt = 0M;
                SaleAmt = CommonService.GetJParamString(jParams, "SaleAmt");
                if (!decimal.TryParse(SaleAmt, out dSaleAmt) || dSaleAmt < 0M)
                {
                    result["Message"] = "参数【dSaleAmt：售券金额】设置错误！";
                    return result.ToString();
                }

                decimal dSettleAmt = 0M;
                SettleAmt = CommonService.GetJParamString(jParams, "SettleAmt");
                if (!decimal.TryParse(SettleAmt, out dSettleAmt) || dSettleAmt < 0M)
                {
                    result["Message"] = "参数【SettleAmt：付款金额】设置错误！";
                    return result.ToString();
                }

                long lSettleId = 0;
                if (dSettleAmt > 0)
                {
                    SettleType = CommonService.GetJParamString(jParams, "SettleType");
                    if (string.IsNullOrWhiteSpace(SettleType))
                    {
                        result["Message"] = "参数【SettleType：支付方式编码】未设置！";
                        return result.ToString();
                    }

                    lSettleId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_PayMode", "FID", "FNumber", SettleType);
                    if (lSettleId == 0)
                    {
                        result["Message"] = "参数【SettleType：支付方式编码】在系统中不存在！";
                        return result.ToString();
                    }
                }

                long lVipId = CommonService.GetBaseDataIdByValue(ctx, "CMK_T_VIP_Member", "FVIPID", "FNumber", VIPNumber);

                //已经消费的礼券不允许发售
                ticketStatus = CommonService.getTicketStatus(ctx, TicketNo);
                if (ticketStatus.Equals("E"))
                {
                    //using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                    //{
                    List<SqlParam> lstParam = new List<SqlParam>();

                    string strSql = @"EXEC CMK_PR_POSTicketSale @BranchID, 1, 1, @BillNo, @VipId, @TransSerial, @TicketNo, @SaleAmt, @SettleAmt, @SettleType, '0', '0', '0', @Note ";
                    lstParam.Add(new SqlParam("@BranchID", KDDbType.String, lBranchId));
                    lstParam.Add(new SqlParam("@VipId", KDDbType.String, lVipId));
                    lstParam.Add(new SqlParam("@BillNo", KDDbType.String, BillNo));
                    lstParam.Add(new SqlParam("@TransSerial", KDDbType.String, TransSerial));
                    lstParam.Add(new SqlParam("@TicketNo", KDDbType.String, TicketNo));
                    lstParam.Add(new SqlParam("@SaleAmt", KDDbType.Decimal, SaleAmt));
                    lstParam.Add(new SqlParam("@SettleAmt", KDDbType.Decimal, dSettleAmt));
                    lstParam.Add(new SqlParam("@SettleType", KDDbType.Int32, lSettleId));
                    lstParam.Add(new SqlParam("@Note", KDDbType.String, Note));

                    //DBUtils.Execute(ctx, strSql, lstParam.ToArray());
                    Data.XDDDBUtils.Execute(strSql, lstParam);

                    //scope.Complete();

                    result["Result"] = true;
                    result["Message"] = "礼券发售成功";
                    //}
                }
                else
                {
                    switch (ticketStatus)
                    {
                        case "C":
                            result["Result"] = false;
                            result["Message"] = "礼券发售失败，原因：该礼券已经消费。";
                            break;
                        case "A":
                            result["Result"] = false;
                            result["Message"] = "礼券发售失败，原因：该礼券发售已经完成，不允许重复提交！";
                            break;
                        case "B":
                            result["Result"] = false;
                            result["Message"] = "礼券发售失败，原因：该礼券已经回收。";
                            break;
                        case "S":
                            result["Result"] = false;
                            result["Message"] = "礼券发售失败，原因：该礼券为待领取。";
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("礼券发售失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 礼券发售冲正
        internal string TicketPublishUndo(Context ctx, string TransSerial, JObject result)
        {
            try
            {
                result["Result"] = false;

                List<SqlParam> lstParam = new List<SqlParam>();
                string strSql = @"SELECT TOP 1 1 FROM CMK_Ticket_ActionFlow WHERE FTRANSSERIAL = @TransSerial ";
                lstParam.Add(new SqlParam("@TransSerial", KDDbType.String, TransSerial));
                //var ticketDatas = DBUtils.ExecuteDynamicObject(ctx, strSql, null, null, CommandType.Text, lstParam.ToArray());
                //if (ticketDatas == null || ticketDatas.Count == 0)
                //{
                //    result["Message"] = "未找到序列号对应的交易信息，交易冲正失败！";
                //    return result.ToString();
                //}

                DataSet ticketDatas = Data.XDDDBUtils.ExecuteDateSet(strSql, lstParam);
                if (ticketDatas == null && ticketDatas.Tables.Count == 0 && ticketDatas.Tables[0].Rows.Count == 0)
                {
                    result["Message"] = "未找到序列号对应的交易信息，交易冲正失败！";
                    return result.ToString();
                }

                //using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                //{
                lstParam = new List<SqlParam>();

                strSql = @"EXEC CMK_PR_POSTicketSaleUndo @TransSerial ";
                lstParam.Add(new SqlParam("@TransSerial", KDDbType.String, TransSerial));

                //DBUtils.Execute(ctx, strSql, lstParam.ToArray());
                Data.XDDDBUtils.Execute(strSql, lstParam);
                //scope.Complete();

                result["Result"] = true;
                result["Message"] = "礼券发售冲正成功";
                //}
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("礼券发售冲正失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 礼券消费
        internal string TicketConsume(Context ctx, string strParams, string TransSerial, JObject result)
        {
            try
            {
                string BranchNumber = "";     //门店编码
                string TicketNo = "";         //礼券编号
                string SettleAmt = "";        //付款金额
                string BillNo = "";           //单据编号
                string ConsumptionSystem = "";//核销来源系统
                string Note = "";             //备注
                string ticketStatus = "";      //礼券状态

                Logger.Info("礼券消费", string.Format("strParams：{0} TransSerial：{1}", strParams, TransSerial));

                result["Result"] = false;
                JObject jParams = JObject.Parse(strParams);

                BranchNumber = CommonService.GetJParamString(jParams, "BranchNumber");
                if (string.IsNullOrWhiteSpace(BranchNumber))
                {
                    result["Message"] = "参数【BranchNumber：门店编码】未设置！";
                    return result.ToString();
                }

                long lBranchId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", BranchNumber);
                if (lBranchId == 0)
                {
                    result["Message"] = "参数【BranchNumber：门店编码】在系统中不存在！";
                    return result.ToString();
                }

                BillNo = CommonService.GetJParamString(jParams, "BillNo");
                if (string.IsNullOrWhiteSpace(BillNo))
                {
                    result["Message"] = "参数【BillNo：单据编号】未设置！";
                    return result.ToString();
                }

                //核销来源系统(新增)
                ConsumptionSystem = CommonService.GetJParamString(jParams, "ConsumptionSystem");
                if (string.IsNullOrWhiteSpace(ConsumptionSystem))
                {
                    result["Message"] = "参数【ConsumptionSystem：核销来源系统】未设置！";
                    return result.ToString();
                }

                Note = CommonService.GetJParamString(jParams, "Note");
                if (string.IsNullOrWhiteSpace(Note))
                {
                    Note = "线上礼券消费接口调用生成";
                }

                TicketNo = CommonService.GetJParamString(jParams, "TicketNo");
                if (string.IsNullOrWhiteSpace(TicketNo))
                {
                    result["Message"] = "参数【TicketNo：礼券编号】未设置！";
                    return result.ToString();
                }

                decimal dSettleAmt = 0M;
                SettleAmt = CommonService.GetJParamString(jParams, "SettleAmt");
                if (!decimal.TryParse(SettleAmt, out dSettleAmt) || dSettleAmt < 0M)
                {
                    result["Message"] = "参数【SettleAmt：付款金额】设置错误！";
                    return result.ToString();
                }
                //直连数据库核销



                //已经消费的礼券不允许发售（走存储过程）
                ticketStatus = CommonService.getTicketStatus(ctx, TicketNo);
                if (!string.IsNullOrWhiteSpace(ticketStatus))
                {
                    if (ticketStatus.Equals("A"))
                    {
                        //using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                        //{
                        List<SqlParam> lstParam = new List<SqlParam>();
                        string strSql = @"EXEC CMK_PR_WebTicketConsume @BranchID, @BillNo, @TicketNo, @Amount, 0, 0, 0, @UserID,@TransSerial,@ConsumptionSystem,@Note ";
                        lstParam.Add(new SqlParam("@BranchID", KDDbType.String, lBranchId));
                        lstParam.Add(new SqlParam("@BillNo", KDDbType.String, BillNo));
                        lstParam.Add(new SqlParam("@TicketNo", KDDbType.String, TicketNo));
                        lstParam.Add(new SqlParam("@Amount", KDDbType.Decimal, dSettleAmt)); //SettleAmt
                        lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, 0));
                        lstParam.Add(new SqlParam("@TransSerial", KDDbType.String, TransSerial));
                        lstParam.Add(new SqlParam("@ConsumptionSystem", KDDbType.String, ConsumptionSystem));
                        lstParam.Add(new SqlParam("@Note", KDDbType.String, Note));

                        //上下文执行
                        //DBUtils.Execute(ctx, strSql, lstParam.ToArray());
                        Data.XDDDBUtils.Execute(strSql, lstParam);

                        //scope.Complete();

                        result["Result"] = true;
                        result["Message"] = "礼券消费成功";
                        //}
                    }
                    else
                    {
                        switch (ticketStatus)
                        {
                            case "C":
                                result["Result"] = false;
                                result["Message"] = "礼券消费失败，原因：该礼券已经消费，不允许重复提交！";
                                break;
                            case "B":
                                result["Result"] = false;
                                result["Message"] = "礼券消费失败，原因：该礼券已经回收。";
                                break;
                            case "O":
                                result["Result"] = false;
                                result["Message"] = "礼券消费失败，原因：该礼券已经过期。";
                                break;
                            case "E":
                                result["Result"] = false;
                                result["Message"] = "礼券消费失败，原因：该礼券为未发行。";
                                break;
                        }
                    }
                }
                else
                {
                    result["Result"] = false;
                    result["Message"] = "礼券消费失败，原因：该礼券不存在。";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("礼券消费失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 礼券消费冲正
        internal string TicketConsumeUndo(Context ctx, string strParams, string TransSerial, JObject result)
        {
            try
            {
                string BranchNumber = "";     //门店编码
                string TicketNo = "";         //礼券编号
                string SettleAmt = "";        //付款金额
                string BillNo = "";           //单据编号

                Logger.Info("礼券消费冲正", string.Format("strParams：{0} TransSerial：{1}", strParams, TransSerial));

                result["Result"] = false;
                JObject jParams = JObject.Parse(strParams);

                BranchNumber = CommonService.GetJParamString(jParams, "BranchNumber");
                if (string.IsNullOrWhiteSpace(BranchNumber))
                {
                    result["Message"] = "参数【BranchNumber：门店编码】未设置！";
                    return result.ToString();
                }

                long lBranchId = CommonService.GetBaseDataIdByValue(ctx, "CMK_LS_Branch", "FID", "FNumber", BranchNumber);
                if (lBranchId == 0)
                {
                    result["Message"] = "参数【BranchNumber：门店编码】在系统中不存在！";
                    return result.ToString();
                }

                BillNo = CommonService.GetJParamString(jParams, "BillNo");
                if (string.IsNullOrWhiteSpace(BillNo))
                {
                    result["Message"] = "参数【BillNo：单据编号】未设置！";
                    return result.ToString();
                }

                TicketNo = CommonService.GetJParamString(jParams, "TicketNo");
                if (string.IsNullOrWhiteSpace(TicketNo))
                {
                    result["Message"] = "参数【TicketNo：礼券编号】未设置！";
                    return result.ToString();
                }

                decimal dSettleAmt = 0M;
                SettleAmt = CommonService.GetJParamString(jParams, "SettleAmt");
                if (!decimal.TryParse(SettleAmt, out dSettleAmt) || dSettleAmt < 0M)
                {
                    result["Message"] = "参数【SettleAmt：付款金额】设置错误！";
                    return result.ToString();
                }
                //冲正前该礼券的礼券状态做判断，若流水记录有消费记录则比较唯一码 2
                if (!string.IsNullOrEmpty(CommonService.getTicketTransSerial(ctx, TicketNo)))
                {
                    if (CommonService.getTicketTransSerial(ctx, TicketNo).Equals(TransSerial))
                    {
                        //using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.RequiresNew))
                        //{
                        List<SqlParam> lstParam = new List<SqlParam>();
                        string strSql = @"EXEC CMK_PR_WebTicketConsumeUndo @BranchID, @BillNo, @TicketNo, @SettleAmt, 0, 0, 0, @UserID, @TransSerial ";
                        lstParam.Add(new SqlParam("@BranchID", KDDbType.String, lBranchId));
                        lstParam.Add(new SqlParam("@BillNo", KDDbType.String, BillNo));
                        lstParam.Add(new SqlParam("@TicketNo", KDDbType.String, TicketNo));
                        lstParam.Add(new SqlParam("@SettleAmt", KDDbType.Decimal, dSettleAmt));
                        lstParam.Add(new SqlParam("@UserID", KDDbType.Int64, 0));
                        lstParam.Add(new SqlParam("@TransSerial", KDDbType.String, TransSerial));

                        //DBUtils.Execute(ctx, strSql, lstParam.ToArray());
                        Data.XDDDBUtils.Execute(strSql, lstParam);
                        //scope.Complete();

                        result["Result"] = true;
                        result["Message"] = "礼券消费冲正成功";
                        //}
                    }
                    else
                    {
                        result["Result"] = false;
                        result["Message"] = "礼券消费冲正失败，原因：该礼券编号冲正唯一码不正确，请查询。";
                    }
                }
                else
                {
                    result["Result"] = false;
                    result["Message"] = "礼券消费冲正失败，原因：该礼券编号不具备冲正条件，请查询。";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("礼券消费冲正失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 常用基础资料查询
        internal string QueryBaseDataInfo(Context ctx, string TableName, string FIDField, JObject result)
        {
            try
            {
                result["Result"] = false;

                string strSql = string.Format(@"SELECT FID, FNumber, FName FROM 
                    (SELECT TOP 500 t1.{1} AS FID, t1.FNumber, t2.FName FROM {0} t1 INNER JOIN {0}_L t2 ON t1.{1} = t2.{1} AND t2.FLocaleId = {2}) t  
                    ", TableName, FIDField, ctx.UserLocale.LCID);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "查询完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("礼券信息查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 会员手机号修改
        public string ModifyVIPMobile(Context ctx, string billData, JObject result)
        {
            try
            {
                result["Result"] = false;
                result["ResCode"] = "204";
                var bill = JObject.Parse(billData);

                long lVipId = 0;
                string VipNumber = CommonService.GetJParamString(bill, "VipNumber");
                if (string.IsNullOrWhiteSpace(VipNumber))
                {
                    result["Message"] = "参数【VipNumber：会员编号】未设置！";
                    return result.ToString();
                }
                lVipId = CommonService.GetBaseDataIdByValue(ctx, "CMK_T_VIP_Member", "FVIPID", "FNumber", VipNumber);
                if (lVipId == 0)
                {
                    result["ResCode"] = "202";
                    result["Message"] = "参数【VipNumber：会员编号】在系统中不存在！";
                    return result.ToString();
                }

                string OldMobile = CommonService.GetJParamString(bill, "OldMobile");
                if (string.IsNullOrWhiteSpace(OldMobile))
                {
                    result["Message"] = "参数【OldMobile：旧手机号】未设置！";
                    return result.ToString();
                }

                string OldSmsCode = CommonService.GetJParamString(bill, "OldSmsCode");
                if (string.IsNullOrWhiteSpace(OldSmsCode))
                {
                    result["Message"] = "参数【OldSmsCode：旧验证码】未设置！";
                    return result.ToString();
                }

                string OldTransSerial = CommonService.GetJParamString(bill, "OldTransSerial");
                if (string.IsNullOrWhiteSpace(OldTransSerial))
                {
                    result["Message"] = "参数【OldTransSerial：旧交易序列号】未设置！";
                    return result.ToString();
                }

                string NewMobile = CommonService.GetJParamString(bill, "NewMobile");
                if (string.IsNullOrWhiteSpace(NewMobile))
                {
                    result["Message"] = "参数【NewMobile：新手机号】未设置！";
                    return result.ToString();
                }

                string NewSmsCode = CommonService.GetJParamString(bill, "NewSmsCode");
                //if (string.IsNullOrWhiteSpace(NewSmsCode))
                //{
                //    result["Message"] = "参数【NewSmsCode：新验证码】未设置！";
                //    return result.ToString();
                //}

                string NewTransSerial = CommonService.GetJParamString(bill, "NewTransSerial");
                //if (string.IsNullOrWhiteSpace(NewTransSerial))
                //{
                //    result["Message"] = "参数【NewTransSerial：新交易序列号】未设置！";
                //    return result.ToString();
                //}

                string strSql = string.Format("SELECT TOP 1 1 FROM CMK_T_VIP_MOBILE_QUEUE WHERE FVIPID = {0} AND TO_CHAR(FLastTime, 'yyyy-MM-dd') = TO_CHAR(GETDATE(), 'yyyy-MM-dd') ", lVipId);
                var vipData = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (vipData != null && vipData.Count > 0)
                {
                    result["ResCode"] = "1011";
                    result["Message"] = "当天已经修改过手机号，不允许重复修改！";
                    return result.ToString();
                }

                strSql = string.Format("SELECT TOP 1 1 FROM CMK_T_VIP_Member WHERE FNumber = '{0}' AND FIsHREmp = '1' ", VipNumber);
                vipData = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (vipData != null && vipData.Count > 0)
                {
                    result["ResCode"] = "1012";
                    result["Message"] = "会员为在职员工，不允许修改手机号！";
                    return result.ToString();
                }

                strSql = string.Format("SELECT TOP 1 1 FROM CMK_T_VIP_Member WHERE FNumber <> '{0}' AND FMobile = '{1}' ", VipNumber, NewMobile);
                vipData = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (vipData != null && vipData.Count > 0)
                {
                    result["ResCode"] = "1013";
                    result["Message"] = "参数【NewMobile：新手机号】已经被其他会员使用，不允许重复！";
                    return result.ToString();
                }

                string strSQL = string.Format("SELECT TOP 1 1 FROM CMK_XH_VIPSmsCode WHERE FTransSerial = '{0}' AND FCode = '{1}' ", OldTransSerial, OldSmsCode);
                var resDatas = DBUtils.ExecuteDynamicObject(ctx, strSQL);
                if (resDatas == null || resDatas.Count == 0)
                {
                    result["ResCode"] = "1014";
                    result["Message"] = string.Format("旧手机号【{0}】验证码【{1}】验证错误！", OldMobile, OldSmsCode);
                    return result.ToString();
                }

                //strSQL = string.Format("SELECT TOP 1 1 FROM CMK_XH_VIPSmsCode WHERE FTransSerial = '{0}' AND FCode = '{1}' ", NewTransSerial, NewSmsCode);
                //resDatas = DBUtils.ExecuteDynamicObject(ctx, strSQL);
                //if (resDatas == null || resDatas.Count == 0)
                //{
                //    result["ResCode"] = "201";
                //    result["Message"] = string.Format("新手机号【{0}】验证码【{1}】验证错误！", NewMobile, NewSmsCode);
                //    return result.ToString();
                //}

                strSQL = string.Format(@"UPDATE CMK_T_VIP_Member SET FMobile = '{0}' WHERE FVIPID = {1}", NewMobile, lVipId);
                DBUtils.Execute(ctx, strSQL);

                strSQL = string.Format(@"INSERT INTO CMK_T_VIP_MOBILE_QUEUE (FVIPID, FOldMobile, FNewMobile, FVersionNo, FTransferNo) VALUES ({0}, '{1}', '{2}', NEWID(), '') ", lVipId, OldMobile, NewMobile);
                DBUtils.Execute(ctx, strSQL);

                JObject jData = new JObject();
                jData.Add("OldMoble", OldMobile);
                jData.Add("NewMoble", NewMobile);

                result["Result"] = true;
                result["ResCode"] = "200";
                result["Data"] = jData;
                result["Message"] = "会员手机号修改成功";

                return result.ToString();
            }
            catch (Exception ex)
            {
                result["Message"] = string.Format("会员手机号修改失败，原因是：{0}", ex.Message);
                return result.ToString();
            }
        }
        #endregion

        #region 查询会员手机号修改记录
        internal string QueryVIPMobileQueue(Context ctx, DateTime dtBegin, DateTime dtEnd, JObject result)
        {
            try
            {
                result["Result"] = false;

                string strSql = string.Format(@"SELECT FVIPID, FVIPNumber, FVIPName, FOldMobile, FNewMobile, FVersionNo, FTransferNo, FLastTime FROM ( 
                    SELECT t1.FVIPID, t2.FNUMBER AS FVIPNumber, t3.FNAME AS FVIPName, t1.FOldMobile, t1.FNewMobile, t1.FVersionNo, t1.FTransferNo, TO_CHAR(t1.FLastTime, 'yyyy-MM-dd HH24:mi:ss') AS FLastTime FROM CMK_T_VIP_MOBILE_QUEUE t1 
	                    INNER JOIN CMK_T_VIP_Member t2 ON t1.FVIPID = t2.FVIPID INNER JOIN CMK_T_VIP_Member_L t3 ON t1.FVIPID = t3.FVIPID AND t3.FLocaleID = {2} 
                    WHERE t1.FLastTime >= '{0}' AND t1.FLastTime < DATEADD(DAY, 1, '{1}') ) t  
                    ", dtBegin, dtEnd, ctx.UserLocale.LCID);
                var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
                if (Datas != null && Datas.Count > 0)
                {
                    result["Result"] = true;
                    result["Message"] = "查询成功";
                    result["Data"] = JArray.FromObject(Datas);
                }
                else
                {
                    result["Result"] = true;
                    result["Message"] = "查询完成，返回查询结果为空！";
                }
            }
            catch (Exception ex)
            {
                result["Result"] = false;
                result["Message"] = string.Format("礼券信息查询失败，原因：{0}", ex.Message);
            }

            return result.ToString();
        }
        #endregion

        #region 检查会员卡使用控制
        internal bool CheckCardUseBranch(Context ctx, long lBranchId, string CardNo, JObject result)
        {
            string strSql = string.Format(@"SELECT TOP 1 FCardId FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDTYPE t2 ON t1.FCARDTYPEID = t2.FCARDTYPEID 
	                LEFT JOIN CMK_T_VIP_CARDTYPECHANNELS t3 ON t2.FCardTypeID = t3.FCardTypeID
                WHERE (t2.FRangeCtrlType = 'A' OR (t2.FRangeCtrlType = 'A' AND t3.FBranchID = {0} AND t3.FIsSelected = '1') 
	                OR (t2.FRangeCtrlType = 'C' AND t1.FBranchID = {0})) AND t1.FNumber = '{1}' ", lBranchId, CardNo);
            DataSet Datas = XDDDBUtils.ExecuteDateSet(strSql);
            //var Datas = DBUtils.ExecuteDynamicObject(ctx, strSql);
            if (Datas != null && Datas.Tables.Count > 0)
            {
                return true;
            }
            else
            {
                result["Result"] = false;
                result["Message"] = string.Format("会员卡【{0}】控制使用门店，不允许在当前门店使用！", CardNo);
                return false;
            }
        }
        #endregion

        #region 修改会员卡密码
        //修改会员卡密码
        internal string QueryCardCustomPassword(Context ctx, string CardNo, string CardPassword, JObject result)
        {
            result["Result"] = false;
            StringBuilder builder = new StringBuilder();
            List<SqlParam> list = new List<SqlParam>();
            string MDPassword = CommonService.Sign(CardPassword);
            builder.AppendLine("UPDATE CMK_T_VIP_CARD SET FCONSUMEPASSWORD=@PassWord WHERE FNUMBER=@CardNo;");
            list.Add(new SqlParam("@PassWord", KDDbType.String, MDPassword));
            list.Add(new SqlParam("@CardNo", KDDbType.String, CardNo));
            //int Datas = DBUtils.Execute(ctx, builder.ToString(), list);
            int ds = XDDDBUtils.Execute(builder.ToString());
            if (ds > 0)
            {

                result["Result"] = true;
                result["Message"] = "会员卡密码修改成功!";
                result["Code"] = 1;
                result["Data"] = MDPassword;
            }
            else
            {
                result["Result"] = false;
                result["Message"] = "会员卡密码修改失败!";
                result["Code"] = 0;
                result["Data"] = "";
            }
            return result.ToString();
        }
        #endregion

        #region 修改小程序会员卡级别（按充值额度进行升级）
        internal string UpdateAppletsHyCardLevel(Context ctx, string CardNo, string CardLevel)
        {
            try
            {
                //查询当前卡号的卡级别
                string sql = string.Format(@"select * from CMK_T_VIP_CARD t1
            inner join CMK_T_VIP_CardLevel t2 on t1.FCARDLEVELID = t2.FCardLevelID
            where t1.FNUMBER = '' and t2.FNUMBER = ''", CardNo, CardLevel);
                var datas = XDDDBUtils.ExecuteDateSet(sql);
                if (datas.Tables != null && datas.Tables[0].Rows.Count > 0)
                {
                    //更新卡级别
                    sql = string.Format(@"update ", "");
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }


            return "";
        }
        #endregion

        //不同模式会员发卡
        private static string CMK_Brand_POSVIPCardPublish(Context ctx, string BusinessMode, string CardNumber, long CardTypeID, long BranchID, string Note, string VIPName, string VIPSex, string VIPBirthday, string VIPPhone, string VIPMobile, string VIPCardKind, string VIPCardID, string VIPEducation, string VIPEmail, string IsSms, string IsCall, string IsEmail, string WorkName, string WorkAddr, string WorkPost, string WorkEmail, string WorkPhone, string WorkDept, string WorkOffice, string WorkTrade, decimal SettleAmt, long SettleType, string WeixinNumber, string WeixinKey, string NeedNewVIP, string VIPNumber, string IntroduceCardNo, string PassWord = "21218CCA77804D2BA1922C33E0151105", string CreateCard = "1")
        {
            DateTime time;
            if (((string.IsNullOrWhiteSpace(CardNumber) || (CardTypeID == 0L)) || (BranchID == 0L)) && (CreateCard == "1"))
            {
                return ResManager.LoadKDString("会员卡号、卡类型或者发卡门店不能为空！", "0033920000000846", SubSystemType.RETAIL, new object[0]);
            }
            long orgIdByBranch = CommonService.GetOrgIdByBranch(ctx, BranchID);
            long num2 = 0L;
            string str2 = "";
            long num3 = 0L;
            string strSQL = string.Format("SELECT TOP 1 FCardID, FCARDSTATUS, FCONTROLBRANCHID FROM CMK_T_VIP_CARD WHERE FNUMBER = '{0}' ", CardNumber);
            DynamicObjectCollection source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
            if ((source != null) && (source.Count > 0))
            {
                num2 = Convert.ToInt64(source.First<DynamicObject>()["FCardID"]);
                str2 = Convert.ToString(source.First<DynamicObject>()["FCARDSTATUS"]);
                num3 = Convert.ToInt64(source.First<DynamicObject>()["FCONTROLBRANCHID"]);
            }
            if (((num2 == 0L) && (NeedNewVIP == "0")) && (CreateCard == "1"))
            {
                return ResManager.LoadKDString("会员卡号在系统中不存在！", "0033920000000848", SubSystemType.RETAIL, new object[0]);
            }
            if (((num2 > 0L) && (str2 != "E")) && (CreateCard == "1"))
            {
                return ResManager.LoadKDString("会员卡号已经发卡！", "0033920000000849", SubSystemType.RETAIL, new object[0]);
            }
            if ((((num2 > 0L) && (CreateCard == "1")) && (num3 > 0L)) && (num3 != BranchID))
            {
                return ResManager.LoadKDString("门店不是该卡指定发卡门店，不允许发行！", "0033920000000850", SubSystemType.RETAIL, new object[0]);
            }
            strSQL = string.Format("SELECT TOP 1 FCardTypeID FROM CMK_T_VIP_CARDTYPE WHERE FCardTypeID = {0} ", CardTypeID);
            source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
            if ((CreateCard == "1") && ((source == null) || (source.Count == 0)))
            {
                return ResManager.LoadKDString("卡类型在系统中不存在！", "0033920000000851", SubSystemType.RETAIL, new object[0]);
            }
            long num4 = 0L;
            long num5 = 0L;
            if (!string.IsNullOrWhiteSpace(IntroduceCardNo))
            {
                strSQL = string.Format("SELECT TOP 1 FVIPMEMBERID, FCardID FROM CMK_T_VIP_CARD WHERE FNUMBER = '{0}' ", IntroduceCardNo);
                source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((source != null) && (source.Count > 0))
                {
                    num4 = Convert.ToInt64(source.First<DynamicObject>()["FVIPMEMBERID"]);
                    num5 = Convert.ToInt64(source.First<DynamicObject>()["FCardID"]);
                }
                if (num5 == 0L)
                {
                    return ResManager.LoadKDString("推荐人卡号不存在，请检查确认！", "0033920000000852", SubSystemType.RETAIL, new object[0]);
                }
            }
            if (!DateTime.TryParse(VIPBirthday, out time))
            {
                VIPBirthday = "1900-01-01";
            }
            if (VIPSex == ResManager.LoadKDString("男", "0033920000000853", SubSystemType.RETAIL, new object[0]))
            {
                VIPSex = "eb28b65afd62405299f061c9173a81de";
            }
            if (VIPSex == ResManager.LoadKDString("女", "0033920000000854", SubSystemType.RETAIL, new object[0]))
            {
                VIPSex = "b589b771e6004d2282fddb03accc7b43";
            }
            int num6 = 0;
            int count = 1;
            List<long> list = new List<long>();
            List<string> sqlArray = new List<string>();
            if (NeedNewVIP == "0")
            {
                strSQL = string.Format("UPDATE CMK_T_VIP_Member AS t1 SET (FIntroduceVIPID, FIntroduceCardID) = (SELECT {0}, {1} \r\n\t\t\t\t    FROM CMK_T_VIP_CARD t2 WHERE t1.FVIPID = t2.FVIPMEMBERID AND t2.FCardID = {2})\r\n\t\t\t    UPDATE CMK_T_VIP_CARD SET FIntroduceCardID = {1} WHERE FCardID = {2}\r\n                ", num4, num5, num2);
                sqlArray.Add(strSQL);
            }
            else
            {
                long num8 = 0L;
                if (!string.IsNullOrWhiteSpace(VIPNumber))
                {
                    strSQL = string.Format("SELECT TOP 1 FVIPID FROM CMK_T_VIP_Member WHERE FNUMBER = '{0}' ", VIPNumber);
                    source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                    if ((source != null) && (source.Count > 0))
                    {
                        num8 = Convert.ToInt64(source.First<DynamicObject>()["FVIPID"]);
                    }
                }
                if (!string.IsNullOrWhiteSpace(VIPMobile))
                {
                    strSQL = string.Format("SELECT TOP 1 FVIPID FROM CMK_T_VIP_Member WHERE FMOBILE = '{0}' ", VIPMobile);
                    source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                    if ((source != null) && (source.Count > 0))
                    {
                        num8 = Convert.ToInt64(source.First<DynamicObject>()["FVIPID"]);
                    }
                }
                if (num8 == 0L)
                {
                    num8 = DBServiceHelper.GetSequenceInt64(ctx, "T_BAS_ITEM", 1).ToList<long>()[0];
                    if (string.IsNullOrWhiteSpace(VIPNumber))
                    {
                        VIPNumber = string.Format("POSVIP{0}", num8);
                    }
                    strSQL = string.Format("INSERT INTO CMK_T_VIP_Member (FVIPID, FFORMID, FMasterId, FNUMBER, FDOCUMENTSTATUS, FFORBIDSTATUS, FCREATEORGID, FUSEORGID, FBRANCHID, \r\n                        FCREATORID, FCREATEDATE, FMODIFIERID, FMODIFYDATE, FCHECKERID, FCHECKDATE, FIDTYPE, FIDNUMBER, FSEX, FBIRTHDAY, FEDUCATION, FTEL, FMOBILE, \r\n\t\t\t\t\t    FEMAIL, FISRECEIVEMOBILEMSG, FISRECEIVEEMAIL, FWORKADDRESS, FWORKZIPCODE, FWEIXIN, FIntroduceVIPID, FIntroduceCardID, FCardIssueStatus)\r\n\t\t\t\t    VALUES ({0}, 'CMK_VIP_MembershipInfo', {0}, '{1}', 'C', 'A', {2}, {2}, {3}, {4}, GETDATE(), {4}, GETDATE(), {4}, GETDATE(), \r\n\t\t\t\t\t    '{5}', {6}, '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}', '{15}', '{16}', '{17}', {18}, {19}, 'B')\r\n                    ", new object[] {
                num8, VIPNumber, orgIdByBranch, BranchID, ctx.UserId, VIPCardKind, num2, VIPSex, VIPBirthday, VIPEducation, VIPPhone, VIPMobile, VIPEmail, IsSms, IsEmail, WorkAddr,
                WorkPost, WeixinKey, num4, num5
            });
                    sqlArray.Add(strSQL);
                    list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_T_VIP_Member_L", 1).ToList<long>();
                    strSQL = string.Format("INSERT INTO CMK_T_VIP_Member_L (FPKID, FVIPID, FLocaleID, FNAME, FDESCRIPTION) VALUES({0}, {1}, {2}, '{3}', '{4}') ", list[0], num8, ctx.UserLocale.LCID, VIPName, Note);
                    sqlArray.Add(strSQL);
                }
                else
                {
                    strSQL = string.Format("UPDATE CMK_T_VIP_Member SET FIntroduceVIPID = {0}, FIntroduceCardID = {1} WHERE FVIPID = {2}", num4, num5, num8);
                    sqlArray.Add(strSQL);
                }
                if (CreateCard == "1")
                {
                    string FCONSUMEPASSWORD = VIPMobile;
                    if (num2 == 0L)
                    {
                        num2 = DBServiceHelper.GetSequenceInt64(ctx, "T_BAS_ITEM", 1).ToList<long>()[0];


                        //卡资料
                        strSQL = string.Format("INSERT INTO CMK_T_VIP_CARD (FCardID, FFORMID, FMasterId, FNUMBER, FDOCUMENTSTATUS, FFORBIDSTATUS, FCREATEORGID, FUSEORGID, FBIZORGID, FBranchID, FCREATORID, FCREATEDATE, FMODIFIERID, FMODIFYDATE, FCHECKERID, FCHECKDATE, \r\n\t\t\t\t\t\t    FCARDTYPEID, FCARDMEDIA, FCARDLEVELID, FVALIDCONTROL, FDATESTART, FDATEEND, \r\n\t\t\t\t\t\t    FCONSUMBYPWD, FCARDSTATUS, FFREEZESTATUS, FVIPMEMBERID, FWEIXINNUMBER, FWEIXINKEY, FCARDISSUINGFEE, FFACEVALUE, FIntroduceCardID, FCONSUMEPASSWORD,FCURRENCYID,FSALEAMOUNT,FCARDKEY)\r\n\t\t\t\t\t    SELECT {0}, 'CMK_VIP_CardInfo', {0}, '{1}', 'C', 'A', {2}, {2}, {2}, {3}, {4}, GETDATE(), {4}, GETDATE(), {4}, GETDATE(),\r\n\t\t\t\t\t\t    FCardTypeID, FCARDMEDIA, FDEFAULTLEVEL, FVALIDCONTROL, CASE WHEN FVALIDCONTROL = '1' THEN TO_CHAR(GETDATE(), 'yyyy-MM-dd') ELSE NULL END, \r\n\t\t\t\t\t\t    CASE WHEN FVALIDCONTROL = '1' THEN TO_CHAR(DATEADD(day, CASE WHEN FVALIDPERIOD > 999999 THEN 999999 ELSE FVALIDPERIOD END, GETDATE()), 'yyyy-MM-dd') ELSE NULL END,\r\n\t\t\t\t\t\t    FCONSUMBYPWD, 'A', 'A', {5}, '{6}', '{7}', FCARDISSUINGFEE, FFACEVALUE, {8}, '{9}' ,FCURRENCYID,FSALEAMOUNT,CASE WHEN ISNULL(FCONSUMBYPWD,0) = '1' THEN '111111' ELSE '' END\r\n\t\t\t\t\t    FROM CMK_T_VIP_CARDTYPE WHERE FCardTypeID = {10}\r\n                        ", new object[] { num2, CardNumber, orgIdByBranch, BranchID, ctx.UserId, num8, WeixinNumber, WeixinKey, num5, PassWord, CardTypeID });
                        sqlArray.Add(strSQL);
                        list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_T_VIP_CARD_L", 1).ToList<long>();
                        strSQL = string.Format("INSERT INTO CMK_T_VIP_CARD_L (FPKID, FCardID, FLocaleID, FNAME, FDESCRIPTION) VALUES({0}, {1}, {2}, '{3}', '{4}') ", list[0], num2, ctx.UserLocale.LCID, CardNumber, Note);
                        sqlArray.Add(strSQL);
                        num6 = 0;
                        count = 1;
                        strSQL = string.Format("SELECT 1 FROM CMK_T_VIP_CARDTYPEACCTS WHERE FCardTypeID = {0} ", CardTypeID);
                        source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                        if ((source != null) && (source.Count > 0))
                        {
                            count = source.Count;
                        }
                        list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_T_VIP_CARDACCTS", count).ToList<long>();
                        foreach (long num9 in list)
                        {
                            num6++;
                            strSQL = string.Format("INSERT INTO CMK_T_VIP_CARDACCTS (FCardID, FEntryID, FSeq, FACCOUNTID, FVALUE, FACCTVALIDCTRL, FACCTDATESTART, FACCTDATEEND, FISLOCK) SELECT {0}, {1}, t1.FSeq, t1.FACCOUNTID, t1.FINITVALUE, t2.FVALIDCONTROL, CASE WHEN t2.FVALIDCONTROL = '1' THEN TO_CHAR(GETDATE(), 'yyyy-MM-dd') ELSE NULL END, CASE WHEN t2.FVALIDCONTROL = '1' THEN TO_CHAR(DATEADD(DAY, CASE WHEN t2.FVALIDPERIOD > 999999 THEN 999999 ELSE t2.FVALIDPERIOD END, GETDATE()), 'yyyy-MM-dd') ELSE NULL END, 'A' FROM CMK_T_VIP_CARDTYPEACCTS t1 INNER JOIN CMK_T_VIP_CARDACCT t2 ON t1.FACCOUNTID = t2.FCardAcctID WHERE t1.FCardTypeID = {2} AND t1.FSeq = {3}", num2, list[num6 - 1], CardTypeID, num6);
                            sqlArray.Add(strSQL);
                        }
                        num6 = 0;
                        count = 1;
                        strSQL = string.Format("SELECT 1 FROM CMK_T_VIP_CARDTYPESRVACCTS WHERE FCardTypeID = {0} ", CardTypeID);
                        source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                        if ((source != null) && (source.Count > 0))
                        {
                            count = source.Count;
                        }
                        list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_T_VIP_CARDACCTS", count).ToList<long>();
                        foreach (long num9 in list)
                        {
                            num6++;
                            strSQL = string.Format("INSERT INTO CMK_T_VIP_CARDSRVACCTS (FCardID, FEntryID, FSeq, FMATERIALID, FCOUNTCTL, FISCONTROLDATE, FACCOUNTDATEBEGIN, FACCOUNTDATEEND, FSRVACCTVALIDPERIOD, FMSTERID, FACCOUNTAMOUNT,FUNITID,FBASEUNITID,FRETAILPRICE,FPRICE,FPAIDAMOUNT) SELECT {0}, {1}, t1.FSeq, t1.FMATERIALID, t1.FCOUNTCTL, t1.FISCONTROLDATE, CASE WHEN t1.FISCONTROLDATE = '1' THEN TO_CHAR(GETDATE(), 'yyyy-MM-dd') ELSE NULL END, CASE WHEN t1.FISCONTROLDATE = '1' THEN TO_CHAR(DATEADD(DAY, CASE WHEN t1.FSRVACCTVALIDPERIOD > 999999 THEN 999999 ELSE t1.FSRVACCTVALIDPERIOD END, GETDATE()), 'yyyy-MM-dd') ELSE NULL END, t1.FSRVACCTVALIDPERIOD, t1.FMSTERID, t1.FACCOUNTAMOUNT ,t1.FUNITID,t1.FBASEUNITID,t1.FRETAILPRICE,t1.FPRICE,t1.FPAIDAMOUNT FROM CMK_T_VIP_CARDTYPESRVACCTS t1 WHERE t1.FCardTypeID = {2} AND t1.FSeq = {3}", num2, list[num6 - 1], CardTypeID, num6);
                            sqlArray.Add(strSQL);
                        }
                    }
                    else
                    {
                        strSQL = string.Format("UPDATE CMK_T_VIP_CARD SET FVIPMEMBERID = {0}, FCARDSTATUS = 'A', FIntroduceCardID = {1}, FCONSUMEPASSWORD = '2', FBranchID = {3}  WHERE FCardID = {4}\r\n\t\t\t\t\t    UPDATE CMK_T_VIP_CARD SET FDATESTART = TO_CHAR(GETDATE(), 'yyyy-MM-dd'), FDATEEND = TO_CHAR(DATEADD(day, CASE WHEN FVALIDPERIOD > 999999 THEN 999999 ELSE FVALIDPERIOD END, GETDATE()), 'yyyy-MM-dd')  \r\n\t\t\t\t\t\t    WHERE FCardID = {4} AND FVALIDCONTROL = '1' ", new object[] { num8, num5, PassWord, BranchID, num2 });
                        sqlArray.Add(strSQL);
                        strSQL = string.Format("UPDATE CMK_T_VIP_CARDACCTS AS t1 SET (FACCTDATESTART, FACCTDATEEND) = (SELECT TO_CHAR(GETDATE(), 'yyyy-MM-dd'), TO_CHAR(DATEADD(day, CASE WHEN t2.FVALIDPERIOD > 999999 THEN 999999 ELSE t2.FVALIDPERIOD END, GETDATE()), 'yyyy-MM-dd')  FROM CMK_T_VIP_CARDACCT t2 WHERE t1.FACCOUNTID = t2.FCardAcctID AND t1.FCardID = {0} AND t1.FACCTVALIDCTRL = '1') ", num2);
                        sqlArray.Add(strSQL);
                        strSQL = string.Format("UPDATE CMK_T_VIP_CARDSRVACCTS AS t1 SET (FACCOUNTDATEBEGIN, FACCOUNTDATEEND) = (SELECT TO_CHAR(GETDATE(), 'yyyy-MM-dd'), TO_CHAR(DATEADD(day, CASE WHEN t2.FSRVACCTVALIDPERIOD > 999999 THEN 999999 ELSE t2.FSRVACCTVALIDPERIOD END, GETDATE()), 'yyyy-MM-dd') FROM CMK_T_VIP_CARDTYPESRVACCTS t2 INNER JOIN CMK_T_VIP_CARD t3 on t2.FCardTypeID = t3.FCARDTYPEID WHERE t1.FMATERIALID = t2.FMATERIALID AND t3.FCardID = t1.FCardID AND t1.FCardID = {0} AND t1.FISCONTROLDATE = '1') ", num2);
                        sqlArray.Add(strSQL);
                    }
                }
                long num10 = 0L;
                num10 = DBServiceHelper.GetSequenceInt64(ctx, "CMK_VIP_CardIssue", 1).ToList<long>()[0];
                string str4 = string.Format("POSFK{0}", num10);
                strSQL = string.Format("INSERT INTO CMK_VIP_CardIssue (FID, FFORMID, FBILLNO, FDOCUMENTSTATUS, FBIZORGID, FBranchID, FCREATORID, FCREATEDATE, FMODIFIERID, FMODIFYDATE, FCHECKERID, FCHECKDATE, \r\n\t\t\t\t\tFCARDTYPEID, FCARDID, FDATESTART, FDATEEND, FCARDISSUINGFEE, FFACEVALUE,  FMEMBERID, FMEMBERNO, FMEMBERIDTYPE, FMEMBERIDNUMBER, FMEMBERSEX, FBIRTHDAY, FEDUCATION,  \r\n\t\t\t\t\tFTEL, FMOBILE, FEMAIL, FISRECEIVEMOBILEMSG, FISRECEIVEEMAIL, FWORKADDRESS, FWORKZIPCODE, FARAMOUNT, FRECEIVEDAMT, FDISCOUNT, FDISCOUNTRATE, FCURRENCYID, \r\n\t\t\t\t\tFRemarks, FFromPos, FCashierID, FPOSID, FINTRODUCEVIPID)\r\n\t\t\t\tSELECT {0}, 'CMK_VIP_CardIssueBill', '{1}', 'C', {2}, {3}, {4}, GETDATE(), {4}, GETDATE(), {4}, GETDATE(),\r\n\t\t\t\t\t{5}, t1.FCardID, t1.FDATESTART, t1.FDATEEND, t1.FCARDISSUINGFEE, t1.FFACEVALUE, t2.FVIPID, t2.FNumber, t2.FIDType, t2.FIDNumber, t2.FSEX, t2.FBIRTHDAY, t2.FEDUCATION, \r\n\t\t\t\t\tt2.FTEL, t2.FMOBILE, t2.FEMAIL, t2.FISRECEIVEMOBILEMSG, t2.FISRECEIVEEMAIL, t2.FWORKADDRESS, t2.FWORKZIPCODE, 0, 0, 0, 0, 1, '{6}', '0', 0, 0, {7}\r\n\t\t\t\tFROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_Member t2 ON t1.FVIPMEMBERID = t2.FVIPID WHERE t1.FCardID = {8}\r\n                ", new object[] { num10, str4, orgIdByBranch, BranchID, ctx.UserId, CardTypeID, Note, num5, num2 });
                sqlArray.Add(strSQL);
                list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_VIP_CardIssue_L", 1).ToList<long>();
                strSQL = string.Format("INSERT INTO CMK_VIP_CardIssue_L (FPKID, FID, FLocaleID, FMEMBERNAME) VALUES({0}, {1}, {2}, '{3}') ", list[0], num10, ctx.UserLocale.LCID, VIPName);
                sqlArray.Add(strSQL);
                list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_VIP_CardIssuePaidEntry", 1).ToList<long>();
                strSQL = string.Format("INSERT INTO CMK_VIP_CardIssuePaidEntry (FID, FEntryID, FSeq, FRECEIVETYPEID, FRECEIVECURRENCYID, FRECEIVEAMT, FEXCHANGETYPEID, FEXCHANGERATE, FLOCRECEIVEAMT)\r\n\t\t\t\tVALUES ({0}, {1}, 1, {2}, 1, {3}, 1, 1, {3}) ", new object[] { num10, list[0], SettleType, SettleAmt });
                sqlArray.Add(strSQL);
                num6 = 0;
                count = 1;
                strSQL = string.Format("SELECT 1 FROM CMK_T_VIP_CARDACCTS WHERE FCardID = {0} ", num2);
                source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((source != null) && (source.Count > 0))
                {
                    count = source.Count;
                }
                list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_VIP_CardIssueAcctEntry", count).ToList<long>();
                foreach (long num9 in list)
                {
                    num6++;
                    strSQL = string.Format("INSERT INTO CMK_VIP_CardIssueAcctEntry (FID, FEntryID, FSeq, FACCOUNTID, FVALUE, FACCTVALIDCTRL, FACCTDATESTART, FACCTDATEEND) SELECT {0}, {1}, t1.FSeq, t1.FACCOUNTID, t1.FVALUE, t1.FACCTVALIDCTRL, t1.FACCTDATESTART, t1.FACCTDATEEND FROM CMK_T_VIP_CARDACCTS t1 WHERE t1.FCardID = {2} AND t1.FSeq = {3}", num10, list[num6 - 1], num2, num6);
                    sqlArray.Add(strSQL);
                }
                num6 = 0;
                list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_VIP_T_CardAction", count).ToList<long>();
                foreach (long num9 in list)
                {
                    num6++;
                    strSQL = string.Format("INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBranchID, FCARDID, FMEMBERID, FACCOUNTID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME,  FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL) SELECT {0}, 'CMK_VIP_CardActionFlow', {1}, '{2}', 'CMK_VIP_CardIssueBill', {3}, {4}, t1.FCardID, t1.FVIPMEMBERID, t2.FACCOUNTID, '1', t2.FVALUE, t2.FVALUE, GETDATE(), GETDATE(), FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS,	FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, '02', {5}, 0, '{6}', ' ' FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDACCTS t2 ON t1.FCardID = t2.FCardID WHERE t1.FCardID = {7} AND t2.FSeq = {8}", list[num6 - 1], num10, str4, orgIdByBranch, BranchID, ctx.UserId, Note, num2, num6);
                    sqlArray.Add(strSQL);
                }
                num6 = 0;
                count = 1;
                strSQL = string.Format("SELECT 1 FROM CMK_T_VIP_CARDSRVACCTS WHERE FCardID = {0} ", num2);
                source = DBUtils.ExecuteDynamicObject(ctx, strSQL, null, null, CommandType.Text, new SqlParam[0]);
                if ((source != null) && (source.Count > 0))
                {
                    count = source.Count;
                }
                list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_VIP_CardIssueSrvAcctE", count).ToList<long>();
                foreach (long num9 in list)
                {
                    num6++;
                    strSQL = string.Format("INSERT INTO CMK_VIP_CardIssueSrvAcctE (FID, FEntryID, FSeq, FMATERIALID, FCOUNTCTL, FISCONTROLDATE, FACCOUNTDATEBEGIN, FACCOUNTDATEEND, FMSTERID, FACCOUNTAMOUNT,FUNITID,FBASEUNITID,FRETAILPRICE,FPRICE,FBASEQTY,FPAIDAMOUNT) SELECT {0}, {1}, t1.FSeq, t1.FMATERIALID, t1.FCOUNTCTL, t1.FISCONTROLDATE, t1.FACCOUNTDATEBEGIN, t1.FACCOUNTDATEEND, t1.FMSTERID, t1.FACCOUNTAMOUNT,t1.FUNITID,t1.FBASEUNITID,t1.FRETAILPRICE,t1.FPRICE,t1.FBASEQTY,t1.FPAIDAMOUNT FROM CMK_T_VIP_CARDSRVACCTS t1 WHERE t1.FCardID = {2} AND t1.FSeq = {3}", num10, list[num6 - 1], num2, num6);
                    sqlArray.Add(strSQL);
                }
                num6 = 0;
                list = DBServiceHelper.GetSequenceInt64(ctx, "CMK_VIP_T_CardAction", count).ToList<long>();
                foreach (long num9 in list)
                {
                    num6++;
                    strSQL = string.Format("INSERT INTO CMK_VIP_T_CardAction (FID, FFORMID, FBILLID, FBILLNO, FBIZTYPE, FORGID, FBranchID, FCARDID, FMEMBERID, FMATERIALID, FOPTION, FOPERVALUE, FBALANCE, FBIZDATE, FRECORDDATETIME, FCARDLEVELID, FCARDSTATUS, FFREEZESTATUS, FVALIDCONTROL, FDATESTART, FDATEEND, FCONSUMBYPWD, FOPERATIONTYPE, FOPERATORID, FPOSID, FNOTE, FTRANSSERIAL, FACCTVALIDCTRL, FACCTDATESTART, FACCTDATEEND) SELECT {0}, 'CMK_VIP_CardActionFlow', {1}, '{2}', 'CMK_VIP_CardIssueBill', {3}, {4}, t1.FCardID, t1.FVIPMEMBERID, t2.FMATERIALID, '1', t2.FCOUNTCTL, t2.FCOUNTCTL, GETDATE(), GETDATE(), t1.FCARDLEVELID, t1.FCARDSTATUS, t1.FFREEZESTATUS, t1.FVALIDCONTROL, t1.FDATESTART, t1.FDATEEND, t1.FCONSUMBYPWD, '02', {5}, 0, '{6}', '', t2.FISCONTROLDATE, t2.FACCOUNTDATEBEGIN, t2.FACCOUNTDATEEND FROM CMK_T_VIP_CARD t1 INNER JOIN CMK_T_VIP_CARDSRVACCTS t2 ON t1.FCardID = t2.FCardID WHERE t1.FCardID = {7} AND t2.FSeq = {8}", list[num6 - 1], num10, str4, orgIdByBranch, BranchID, ctx.UserId, Note, num2, num6);
                    sqlArray.Add(strSQL);
                }
                strSQL = string.Format("UPDATE CMK_T_VIP_MEMBER SET FCARDISSUESTATUS = 'B' WHERE FVIPID = {0} ", num8);
                sqlArray.Add(strSQL);
            }
            using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.Required))
            {
                if (sqlArray.Count > 0)
                {
                    DBUtils.ExecuteBatch(ctx, sqlArray, sqlArray.Count);
                    sqlArray.Clear();
                }
                scope.Complete();
            }
            return "";
        }

    }
}
